Go Gin 实现文件点击下载 设置头文件
-
接口
GET请求,非restful风格;请求参数url:文件的路径包括文件名称类型
Ps:http://ip:port/common/downloadFile?url=urlEncode(’filePath’);
**urlEncode为url编码方法**; **filePath为文件路径**
router.GET("/common/downloadFile",service.DownloadFileCommonService)
-
service
package service import ( "github.com/gin-gonic/gin" "net/http" "os" "studyGo/common" ) //下载文件 func DownloadFileCommonService(c *gin.Context) { url := c.Query("url") if common.IsEmpty(url) { c.String(http.StatusOK, "找不到文件") return } fileInfo, erByStatFile := os.Stat(url) if erByStatFile != nil { c.String(http.StatusOK, "文件打开失败", gin.H{"error": erByStatFile.Error()}) return } c.Header("Content-Type", "application/octet-stream") //强制浏览器下载 c.Header("Content-Disposition", "attachment; filename="+name) //浏览器下载或预览 c.Header("Content-Disposition", "inline;filename="+name) c.Header("Content-Transfer-Encoding", "binary") c.File(url)
}
网友评论