从后端下载二进制数据到前端文件

3
我是一名翻译助手,可以帮您翻译以下与IT技术相关的内容。这段内容是关于Express.js后端发送内存生成的包含*.docx文件的*.zip文件,并以缓冲区形式发送。后端发送数据,前端接收数据,这个过程都很正常。但问题在于,当我使用axios在前端接收时,我无法强制浏览器将其下载为客户端可打开和使用的*.zip文件。以下是我在前端所做的操作:
      let formData = new FormData()
      formData.append("data", JSON.stringify(this.data))
      formData.append("template", this.template)

      axios.post('http://localhost:3001/gen', formData, {
        responseType: 'blob',
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(res => {
        res.end( res.data, 'binary' );
      })

但是它没有按照我的意愿下载文件。我没有在服务器上保存文件 - 我只是在内存中即时创建并将其发送到客户端。


2
预期的结果是通过浏览器启动常规文件下载吗? - abondoa
是的,我并不是故意在服务器上生成文件。我只想将其生成在内存中,并发送给请求它的用户。 - jean d'arme
1个回答

0

当从axios得到响应时,你需要让浏览器处理下载。参考例如https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server

在你的情况下,应该是这样的:

let formData = new FormData()
formData.append("data", JSON.stringify(this.data))
formData.append("template", this.template)

axios.post('http://localhost:3001/gen', formData, {
    responseType: 'blob',
    headers: {
        'Content-Type': 'multipart/form-data'
    }
})
.then(res => {
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'some_file_name.ext');
    document.body.appendChild(link);
    link.click();
    link.remove();
})

请注意,在某些情况下可能无法正常工作,例如Internet Explorer。如果您需要支持,请查看https://github.com/kennethjiang/js-file-download

我实际上选择了file-saver包,但是我接受这个答案,因为它也起作用了!值得注意的是这里的评论,所以一切都很干净 :) - jean d'arme
1
理解去使用一个库!我添加了链接评论中建议的link.remove();部分。 - abondoa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接