node.js - 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 中打开。
解决方案
稍微摆弄一下 axios.get 语法,将“responseType”与具有标题的配置放在一起。现在我得到的文件没有损坏o_o
axios.get(`api/` + file.id,
{
headers:
{
'x-access-token': token
},
responseType: 'arraybuffer'
}
)
起初我以为文件大小不同,但事实并非如此。所以这肯定解决了它哈哈。这就是我从 js 中的菜鸟中得到的。
推荐阅读
- sql - 如何在表中查找计算字段
- windows - 暴露一个
/ 上网 - java - 如何将 .properties 文件从父项目共享到子项目
- angular - 从 firebase 获取文件
- android - 如何在 Android Studio 中强制执行 Android APK 的安全二进制属性?
- swift - 如何使用 onSnapshot() 方法快速正确地利用 Firestore 实时更新?
- reactjs - ReactJS:通用cookie无法读取cookie
- c# - 从 Winforms 应用程序调用 CameraCaptureUI
- python - 在 Python 中编写单行嵌套循环
- pygame - 你如何解决:“AttributeError:'int'对象没有属性'world_shift'”