go gin
/*downloadFile 通用API,比如,下载文件,大家都可以调用这个api*/
func downloadFile(c *gin.Context) {
fmt.Println(c.Request.URL)
//filePath := c.Query("path")
requestURL := fmt.Sprintf("%v", c.Request.URL)
requestURLarray := strings.Split(requestURL, "url=")
if len(requestURLarray) < 2 {
sbjlog.Debug("downloadFile 失败 文件地址:%s ", requestURL)
return
}
filePath := requestURLarray[1]
filePath = "./" + filePath
//打开文件
fileTmp, errByOpenFile := os.Open(filePath)
if errByOpenFile != nil {
sbjlog.Debug("downloadFile 失败 文件地址:%s 异常:%v", filePath, errByOpenFile)
c.Redirect(http.StatusFound, "/404")
return
}
defer fileTmp.Close()
//获取文件的名称
fileName := path.Base(filePath)
isExit, err := PathExists(filePath)
if err != nil {
sbjlog.Debug("downloadFile 失败 文件地址:%s 异常:%v", filePath, err)
c.Redirect(http.StatusFound, "/404")
return
}
if !isExit {
sbjlog.Debug("downloadFile 失败 文件地址:%s ", filePath)
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
}
authorized.GET("/file/download", downloadFile) //下载文件
vue
handleFileCardPreview(file) {
//file.url= http://localhost:9527/api/file/download?url=/file/department/job/20210715154148_1564.docx
if (file.url && file.url.indexOf('/api/file/download?url=') == 0) {
window.location.href = file.url
} else {
this.$message.warning('文件' + file.name + '已暂存成功,请保存后查看')
}
},