React + Node Express,下载的docx文件已损坏

时间:2020-02-05 16:43:39

标签: node.js reactjs download axios

我已经阅读了许多类似的问题,尝试了许多建议的解决方案,但没有一个对我有用。因此,我使用“ res.download('directory /'+文件名)”从后端发送文件,并从响应头判断,我确实获得了正确的文件。我要从中发送的文件夹中没有其他文件,原始文件为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,并且由于损坏而无法用文字打开。

2 个答案:

答案 0 :(得分:1)

您可能需要在文件名的末尾添加文件扩展名,如下所示:

 link.setAttribute('download', `${filename}.docx`);

答案 1 :(得分:0)

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

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

起初我以为文件大小是不同的,但事实并非如此。所以一定要修复它。这就是我成为js菜鸟后所得到的。

相关问题