首頁 > 軟體

Go Gin實現檔案上傳下載的範例程式碼

2021-04-02 13:01:36

Go Gin 實現檔案的上傳下載流讀取

檔案上傳

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")
 //處理獲取檔案錯誤
 if errFile != nil || common.IsEmpty(header.Filename) {
   c.JSON(http.StatusOK, gin.H{
     "success": false,
     "message": "請選擇檔案",
     "dir":   saveDir,
     "name":  saveName,
     "path":  savePath,
   })
   return
 }
 //目錄請求引數為空
 if common.IsEmpty(saveDirParam) {
   c.JSON(http.StatusOK, gin.H{
     "success": false,
     "message": "請求引數錯誤!",
     "dir":   saveDir,
     "name":  saveName,
     "path":  savePath,
   })
   return
 }
 //如果上傳的名稱為空,則自動生成名稱
 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() {
   //建立目錄
   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": "建立目錄失敗",
     })
     return
   }
 }
 ////上傳檔案前 先刪除該資源之前上傳過的資原始檔
 ////(編輯-重新選擇檔案-需要先刪除該資源之前上傳過的資原始檔)
  ////該程式碼執行的條件----上傳的名稱是唯一的,否則會出現誤刪
 ////獲取檔案的字首
 //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
 }

 //沒有錯誤的情況下
 c.JSON(http.StatusOK, gin.H{
   "success": true,
   "dir":   saveDir,
   "name":  saveName,
   "path":  savePath,
   "message": "上傳成功",
 })
 return
}

js提交例子:

注:需匯入jquery.js 和 ajaxfileupload.js

//上傳檔案
    $.ajaxFileUpload(
      {
        url: '/resources/common/upload', //用於檔案上傳的伺服器端請求地址
        secureuri: false, //是否需要安全協定,一般設定為false
        fileElementId: fileUploadDomId, //檔案上傳域的ID
        data: {
          "saveDir":fileSaveDir,
          "fileName":fileSaveName
        },
        dataType: 'json', //返回值型別 一般設定為json
        contentType:'application/json',//提交的資料型別
        async: false,
        success: function (data, status) //伺服器成功響應處理常式
        {
          if (data.success){
            fileSaveName=fileSaveDir+"/"+data.name;
            console.log("上傳成功,返回的檔案的路徑:",fileSaveName)
          }else{
            console.log("上傳失敗,返回的檔案的路徑:",fileSaveName)
            return
          }
        },
        error: function (data, status, e)//伺服器響應失敗處理常式
        {
          console.log("e==",e);
          return
        }
      }
    );

檔案的下載

router

Type:‘GET'

普通連結格式非restful風格

引數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

//下載次數
func UserFileDownloadCommonService(c *gin.Context) {
  filePath := c.Query("url")
 //開啟檔案
 fileTmp, errByOpenFile := os.Open(filePath)
 defer fileTmp.Close()
  
  //獲取檔案的名稱
  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")
   //強制瀏覽器下載
 c.Header("Content-Disposition", "attachment; filename="+fileName)
 //瀏覽器下載或預覽
 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風格

引數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 檔案型別對應的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",
}

//根據檔案路徑讀取返回流檔案 引數url
func PubResFileStreamGetService(c *gin.Context) {
filePath := c.Query("url")
//獲取檔名稱帶字尾
fileNameWithSuffix := path.Base(filePath)
//獲取檔案的字尾
fileType := path.Ext(fileNameWithSuffix)
//獲取檔案型別對應的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)
}

到此這篇關於Go Gin實現檔案上傳下載的範例程式碼的文章就介紹到這了,更多相關Go Gin 檔案上傳下載內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com! 


IT145.com E-mail:sddin#qq.com