Go Gin實(shí)現(xiàn)文件上傳下載的示例代碼
Go Gin 實(shí)現(xiàn)文件的上傳下載流讀取
文件上傳
router
router.POST("/resources/common/upload", service.UploadResource)
service
type: POST
data:{ “saveDir”:“保存的路徑”, “fileName”:“文件名稱(chēng)不帶后綴” }
// 上傳文件 func UploadResource(c *gin.Context) { saveDirParam := c.PostForm("saveDir") // 文件目錄 fileNameParam := c.PostForm("fileName") // 文件名稱(chēng) //目錄 var saveDir = "" //名稱(chēng) var saveName = "" //完整路徑 var savePath = "" //獲取文件 file, header, errFile := c.Request.FormFile("file") //處理獲取文件錯(cuò)誤 if errFile != nil || common.IsEmpty(header.Filename) { c.JSON(http.StatusOK, gin.H{ "success": false, "message": "請(qǐng)選擇文件", "dir": saveDir, "name": saveName, "path": savePath, }) return } //目錄請(qǐng)求參數(shù)為空 if common.IsEmpty(saveDirParam) { c.JSON(http.StatusOK, gin.H{ "success": false, "message": "請(qǐng)求參數(shù)錯(cuò)誤!", "dir": saveDir, "name": saveName, "path": savePath, }) return } //如果上傳的名稱(chēng)為空,則自動(dòng)生成名稱(chēng) if common.IsEmpty(fileNameParam) { fileNameParam = GenerateResourceNo() } //獲取上傳文件的后綴(類(lèi)型) uploadFileNameWithSuffix := path.Base(header.Filename) uploadFileType := path.Ext(uploadFileNameWithSuffix) //文件保存目錄 saveDir = "/attachment" + saveDirParam //保存的文件名稱(chēng) saveName = fileNameParam + uploadFileType savePath = saveDir + "/" + saveName //打開(kāi)目錄 localFileInfo, fileStatErr := os.Stat(saveDir) //目錄不存在 if fileStatErr != nil || !localFileInfo.IsDir() { //創(chuàng)建目錄 errByMkdirAllDir := os.MkdirAll(saveDir, 0755) if errByMkdirAllDir != nil { logs.Error("%s mkdir error.....", saveDir, errByMkdirAllDir.Error()) c.JSON(http.StatusOK, gin.H{ "success": false, "dir": saveDir, "name": saveName, "path": savePath, "message": "創(chuàng)建目錄失敗", }) return } } ////上傳文件前 先刪除該資源之前上傳過(guò)的資源文件 ////(編輯-重新選擇文件-需要先刪除該資源之前上傳過(guò)的資源文件) ////該代碼執(zhí)行的條件----上傳的名稱(chēng)是唯一的,否則會(huì)出現(xiàn)誤刪 ////獲取文件的前綴 //fileNameOnly := fileNameParam //deleteFileWithName(fileNameOnly, saveDir) //deleteFileWithName(fileNameOnly, model.WebConfig.ResourcePath+"/"+ // model.WebConfig.WebConvertToPath) out, err := os.Create(savePath) if err != nil { logs.Error(err) } defer out.Close() _, err = io.Copy(out, file) if err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, "dir": saveDir, "name": saveName, "path": savePath, "message": err.Error(), }) return } //沒(méi)有錯(cuò)誤的情況下 c.JSON(http.StatusOK, gin.H{ "success": true, "dir": saveDir, "name": saveName, "path": savePath, "message": "上傳成功", }) return }
js提交例子:
注:需導(dǎo)入jquery.js 和 ajaxfileupload.js
//上傳文件 $.ajaxFileUpload( { url: '/resources/common/upload', //用于文件上傳的服務(wù)器端請(qǐng)求地址 secureuri: false, //是否需要安全協(xié)議,一般設(shè)置為false fileElementId: fileUploadDomId, //文件上傳域的ID data: { "saveDir":fileSaveDir, "fileName":fileSaveName }, dataType: 'json', //返回值類(lèi)型 一般設(shè)置為json contentType:'application/json',//提交的數(shù)據(jù)類(lèi)型 async: false, success: function (data, status) //服務(wù)器成功響應(yīng)處理函數(shù) { if (data.success){ fileSaveName=fileSaveDir+"/"+data.name; console.log("上傳成功,返回的文件的路徑:",fileSaveName) }else{ console.log("上傳失敗,返回的文件的路徑:",fileSaveName) return } }, error: function (data, status, e)//服務(wù)器響應(yīng)失敗處理函數(shù) { console.log("e==",e); return } } );
文件的下載
router
Type:‘GET'
普通鏈接格式非restful風(fēng)格
參數(shù)url:下載的文件的路徑
- Jquery解碼:decodeURIComponent(url);
- Jquery編碼:encodeURIComponent(url);
例:http://127.0.0.0.1:8080//pub/common/download?url=“/attachment/demo.docx”
router.GET("/pub/common/download", service.PubResFileStreamGetService)
service
//下載次數(shù) func UserFileDownloadCommonService(c *gin.Context) { filePath := c.Query("url") //打開(kāi)文件 fileTmp, errByOpenFile := os.Open(filePath) defer fileTmp.Close() //獲取文件的名稱(chēng) fileName:=path.Base(filePath) if common.IsEmpty(filePath) || common.IsEmpty(fileName) || errByOpenFile != nil { logs.Error("獲取文件失敗") c.Redirect(http.StatusFound, "/404") return } c.Header("Content-Type", "application/octet-stream") //強(qiáng)制瀏覽器下載 c.Header("Content-Disposition", "attachment; filename="+fileName) //瀏覽器下載或預(yù)覽 c.Header("Content-Disposition", "inline;filename="+fileName) c.Header("Content-Transfer-Encoding", "binary") c.Header("Cache-Control", "no-cache") c.File(filePath) return }
文件流讀取
router
Type:‘GET'
普通鏈接格式非restful風(fēng)格
參數(shù)url:下載的文件的路徑
- Jquery解碼:decodeURIComponent(url);
- Jquery編碼:encodeURIComponent(url);
例:http://127.0.0.0.1:8080//pub/common/file_stream?url=“/attachment/demo.docx”
router.GET("/pub/common/file_stream", service.PubResFileStreamGetService)
service
//map for Http Content-Type Http 文件類(lèi)型對(duì)應(yīng)的content-Type var HttpContentType = map[string]string{ ".avi": "video/avi", ".mp3": " audio/mp3", ".mp4": "video/mp4", ".wmv": " video/x-ms-wmv", ".asf": "video/x-ms-asf", ".rm": "application/vnd.rn-realmedia", ".rmvb": "application/vnd.rn-realmedia-vbr", ".mov": "video/quicktime", ".m4v": "video/mp4", ".flv": "video/x-flv", ".jpg": "image/jpeg", ".png": "image/png", } //根據(jù)文件路徑讀取返回流文件 參數(shù)url func PubResFileStreamGetService(c *gin.Context) { filePath := c.Query("url") //獲取文件名稱(chēng)帶后綴 fileNameWithSuffix := path.Base(filePath) //獲取文件的后綴 fileType := path.Ext(fileNameWithSuffix) //獲取文件類(lèi)型對(duì)應(yīng)的http ContentType 類(lèi)型 fileContentType := HttpContentType[fileType] if common.IsEmpty(fileContentType) { c.String(http.StatusNotFound, "file http contentType not found") return } c.Header("Content-Type", fileContentType) c.File(filePath) }
到此這篇關(guān)于Go Gin實(shí)現(xiàn)文件上傳下載的示例代碼的文章就介紹到這了,更多相關(guān)Go Gin 文件上傳下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
go實(shí)現(xiàn)一個(gè)內(nèi)存緩存系統(tǒng)的示例代碼
本文主要介紹了go實(shí)現(xiàn)一個(gè)內(nèi)存緩存系統(tǒng)的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-10-10go?defer延遲調(diào)用的使用場(chǎng)景示例詳解
這篇文章主要為大家介紹了go?defer延遲調(diào)用的使用場(chǎng)景示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05Go語(yǔ)言json編碼駝峰轉(zhuǎn)下劃線、下劃線轉(zhuǎn)駝峰的實(shí)現(xiàn)
這篇文章主要介紹了Go語(yǔ)言json編碼駝峰轉(zhuǎn)下劃線、下劃線轉(zhuǎn)駝峰的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06golang反向代理設(shè)置host不生效的問(wèn)題解決
在使用golang的httputil做反向代理的時(shí)候,發(fā)現(xiàn)一個(gè)奇怪的現(xiàn)象,上游網(wǎng)關(guān)必須要設(shè)置host才行,不設(shè)置host的話,golang服務(wù)反向代理請(qǐng)求下游會(huì)出現(xiàn)http 503錯(cuò)誤,接下來(lái)通過(guò)本文給大家介紹golang反向代理設(shè)置host不生效問(wèn)題,感興趣的朋友一起看看吧2023-05-05利用Go語(yǔ)言實(shí)現(xiàn)Raft日志同步
這篇文章主要為大家詳細(xì)介紹了如何利用Go語(yǔ)言實(shí)現(xiàn)Raft日志同步,文中的示例代碼講解詳細(xì),對(duì)我們深入了解Go語(yǔ)言有一定的幫助,需要的可以參考一下2023-05-05