用Django和Vue强制下载

时间:2018-01-01 04:43:22

标签: django vue.js axios force-download

我尝试使用vue从服务器下载文件

当导演访问我的后端API时,它运行良好,我可以正常解压缩文件。

但是当我尝试通过axios响应下载文件时,文件无法解压缩,而且如果我没有设置link.download,则文件名不正确。 enter image description here

这是我的vi&#39> api

export function packMaterials (context, thesisId, filename) {
  context.$axios({
    method: 'get',
    headers: getAuthHeader(),
    url: PACK_URL + thesisId
  })
    .then(function (response) {
      console.log(response)
      let blob = new Blob([response.data], { type: 'application/force-download' })
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = filename
      link.click()
    })
    .catch(function (error) {
      console.log(error)
    })
}

这是我的Django API

 if os.path.exists(file_path):
    # 返回file
    with open(file_path, 'rb') as fh:
        response = HttpResponse(fh.read(), content_type="application/force-download")
        response['Content-Disposition'] = "attachment; filename={}".format(escape_uri_path(filename))
        return response

这是控制台中的响应数据。 enter image description here 英语不是我的母语,所以如果我的描述不清楚,你可以通过lc960127@gmail.com与我联系。我会发送更多细节。

感谢

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。 看来您只需要将 axios resposeType 配置为 'blob':

axios({
    method: 'get’,
    responseType: ‘blob’, // <— Change here
    headers: getAuthHeader(),
    url: PACK_URL + thesisId
})