路由配置

1
2
//文件下载
router.GET("/download", DownloadFileService)

控制层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
下载文件
*/
func DownloadFileService(c *gin.Context) {
fileDir := "./static/export/"
fileName := c.Query("file")
//打开文件
fileSource, errByOpenFile := os.Open(fileDir + fileName)
//非空处理
if helper.IsEmpty(fileDir) || helper.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)
//一定要关闭文件 否则文件资源会一直被占用
fileSource.Close()

return
}

访问连接

1
www.xxxx.com/download?file=xxxx.csv