Go Gin 實(shí)現(xiàn)文件的上傳下載流讀取
文件上傳
-
router
router.POST("/resources/common/upload", service.UploadResource)
-
service
type: POST
data:{
? “saveDir”:“保存的路徑”悍抑,
? “fileName”:“文件名稱不帶后綴”
? }
// 上傳文件 func UploadResource(c *gin.Context) { saveDirParam := c.PostForm("saveDir") // 文件目錄 fileNameParam := c.PostForm("fileName") // 文件名稱 //目錄 var saveDir = "" //名稱 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 } //如果上傳的名稱為空训桶,則自動(dòng)生成名稱 if common.IsEmpty(fileNameParam) { fileNameParam = GenerateResourceNo() } //獲取上傳文件的后綴(類型) uploadFileNameWithSuffix := path.Base(header.Filename) uploadFileType := path.Ext(uploadFileNameWithSuffix) //文件保存目錄 saveDir = "/attachment" + saveDirParam //保存的文件名稱 saveName = fileNameParam + uploadFileType savePath = saveDir + "/" + saveName //打開目錄 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 } } ////上傳文件前 先刪除該資源之前上傳過的資源文件 ////(編輯-重新選擇文件-需要先刪除該資源之前上傳過的資源文件) ////該代碼執(zhí)行的條件----上傳的名稱是唯一的樊零,否則會(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 } //沒有錯(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', //返回值類型 一般設(shè)置為json contentType:'application/json',//提交的數(shù)據(jù)類型 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") //打開文件 fileTmp, errByOpenFile := os.Open(filePath) defer fileTmp.Close() //獲取文件的名稱 fileName:=path.Base(filePath) c.Header("Content-Type", "application/octet-stream") c.Header("Content-Disposition", "attachment; filename="+fileName) c.Header("Content-Transfer-Encoding", "binary") c.Header("Cache-Control", "no-cache") if common.IsEmpty(filePath) || common.IsEmpty(fileName) || errByOpenFile != nil { logs.Error("獲取文件失敗") c.Redirect(http.StatusFound, "/404") return } c.Header("Content-Type", "application/octet-stream") c.Header("Content-Disposition", "attachment; filename="+fileName) c.Header("Content-Transfer-Encoding", "binary") 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 文件類型對(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")
//獲取文件名稱帶后綴
fileNameWithSuffix := path.Base(filePath)
//獲取文件的后綴
fileType := path.Ext(fileNameWithSuffix)
//獲取文件類型對(duì)應(yīng)的http ContentType 類型
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)
}