我的express.js代码非常简单:
app.get("/download", download);
和
export let download = async (req: Request, res: Response) => {
const file = "/tmp/my-file.zip";
res.download(file);
}
我的客户代码也很简单:
import axios from "axios";
const fileDownload = require("js-file-download");
axios.get("/download").then(response => {
fileDownload(response.data, "export.zip");
});
从浏览器下载时,文件已损坏,我无法打开它。原始/tmp/my-file.zip
为119506
字节。奇怪的是,下载的export.zip
是216980
字节。我目前正在本地运行所有程序,因此没有操作系统差异可以解释这一点。
为什么我的文件大小不同(导致损坏的.zip文件),该如何解决?
编辑-这些是浏览器标题:
accept-ranges: "bytes"
cache-control: "no-store, no-cache, must-revalidate, proxy-revalidate"
connection: "keep-alive"
content-disposition: "attachment; filename="my-file.zip""
content-length: "119506"
content-type: "application/zip"
date: "Thu, 14 Mar 2019 06:04:28 GMT"
etag: "W/"1d2d2-1697acd3f53""
expires: "0"
last-modified: "Thu, 14 Mar 2019 06:04:25 GMT"
pragma: "no-cache"
referrer-policy: "no-referrer"
surrogate-control: "no-store"
x-content-type-options: "nosniff"
x-frame-options: "SAMEORIGIN"
x-xss-protection: "1; mode=block"
答案 0 :(得分:1)
我在此post找到了解决方案。因为axios responseType的默认值为json
//
responseType
表示服务器将要处理的数据类型 用//响应//选项是'arraybuffer','blob','document', 'json','text','stream'responseType:'json',//默认值
axios.get('/download',{ responseType:'arraybuffer'})
.then(function (response) {
console.log('########### HEADERS: ', response.headers);
console.log('########### AXIOS: ', response.data.length);
fileDownload(response.data, "export.zip");
});
希望它能起作用:)