首页 > 解决方案 > React+Node Express,下载的 docx 文件损坏

问题描述

我已经阅读了很多类似的问题,尝试了很多建议的解决方案,但没有一个对我有用。所以,我使用“res.download('directory/' + filename)”从后端发送文件,从响应头来看,我确实得到了正确的文件。我发送的文件夹中没有其他文件,原始文件为 14KB。然而,响应的“数据”部分约为 21KB。这就是我对 Web 应用程序响应以获取文件所做的操作:

await axios.get(`api` + file.id, 
        {headers: {'x-access-token': token}}, { responseType: 'arraybuffer' }
    ).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data])); //specifying the type here doesn't help
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `${filename}`); //filename = the name of the file i'm trying to download
        document.body.appendChild(link);
        link.click();
        link.parentNode.removeChild(link);
    })

我在结果中得到的文件也大约 21KB,并且由于它已损坏而无法在 word 中打开。

标签: node.jsreactjsdownloadaxios

解决方案


稍微摆弄一下 axios.get 语法,将“responseType”与具有标题的配置放在一起。现在我得到的文件没有损坏o_o

axios.get(`api/` + file.id, 
  {
    headers: 
    {
      'x-access-token': token
    },
    responseType: 'arraybuffer' 
  }
)

起初我以为文件大小不同,但事实并非如此。所以这肯定解决了它哈哈。这就是我从 js 中的菜鸟中得到的。


推荐阅读