tiger1103 / gfast

基于GF(Go Frame)的后台管理系统
http://www.g-fast.cn/
Apache License 2.0
1.66k stars 400 forks source link

请问下下载文件怎么做 #42

Closed songning4 closed 2 years ago

songning4 commented 2 years ago

我用get请求,到服务端后需要下载文件,使用以下代码,浏览器并不会弹出下载,请问应该怎么做,谢谢

        file := "git-" + todayDate + ".xlsx"

    // 读取文件
    downFile := gfile.GetBytes(file)

    req.Response.Header().Set("Content-Type", "application/octet-stream")
    req.Response.Header().Set("Content-Disposition", "attachment; filename="+file)
    req.Response.Write(downFile)
        req.Exit()
iShot2021-12-23 17 10 05 iShot2021-12-23 17 11 00
tiger1103 commented 2 years ago

要么直接在新标签打开文件地址,浏览器会自动下载。 如果你要用api请求文件返回数据流,需要js来处理生成文件,具体参考:

import axios from 'axios'
import { getToken } from '@/utils/auth'

const mimeMap = {
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  zip: 'application/zip'
}

const baseUrl = process.env.VUE_APP_BASE_API
export function downLoadZip(str, filename) {
  var url = baseUrl + str
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() }
  }).then(res => {
    if(filename){
      res.headers['content-disposition'] = 'attachment; filename='+filename;
    }
    resolveBlob(res, mimeMap.zip)
  })
}
/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, mimeType) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition']||res.headers['Content-Disposition'])
  var result = patt.exec(contentDisposition)
  var fileName = result[1]
  fileName = fileName.replace(/\"/g, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}