golang+gin实现文件下载GET接口API
2021-02-18 本文已影响0人
五岁小孩
golang+gin 实现文件下载GET接口api
-
1.api接口格式
http://ip:port/downloadFiles
-
2.接口router
http url: http://ip:port/downloadFiles?filedir=attachment/resource&fileName=name.jpg
param: filedir: 文件路径
fileName:文件名称
router.GET("/downloadFiles",service.DownloadFileService)
-
3.service
//TODO Test资源文件下载 func DownloadFileService(c *gin.Context) { fileDir := c.Query("fileDir") fileName := c.Query("fileName") //打开文件 _, errByOpenFile := os.Open(fileDir + "/" + fileName) //非空处理 if common.IsEmpty(fileDir) || common.IsEmpty(fileName) || errByOpenFile != nil { /*c.JSON(http.StatusOK, gin.H{ "success": false, "message": "失败", "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(fileDir + "/" + fileName) return }