gin+vue 上传 下载文件

20 篇文章 0 订阅

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 + '已暂存成功,请保存后查看')
      }
    },

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值