我已经在这个问题上苦苦挣扎了一段时间了,需要你们的帮助!我正在尝试简化从我的网站下载报告的过程。对于 Node 来说,使用 readStream 就相当简单了,如下所示:
router.post('/report', (req, res) => {
const filename = 'test.png';
const filePath = path.join(__dirname, filename);
fs.exists(filePath, exists => {
if (exists) {
const stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': stat.size,
'Content-Disposition': 'attachment; filename=' + filename,
});
fs.createReadStream(filePath).pipe(res);
} else {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('ERROR File does NOT Exists');
}
});
});
现在,如果我使用 Postman 或其他一些 API 测试器尝试此操作,它会完美运行,文件会正确下载并保存。现在我正在努力让它在我的前端工作。我目前正在运行 AngularJS 并尝试使用 FileSaver.js作为获取这些数据并保存它的一种方法,但它从来没有起作用。文件已保存,但数据不可读,即图像预览器显示图像已损坏。我认为我错误地创建了 Blob?
function exportReport(_id) {
this.$http
.post(
'/api/report',
{ _id },
{
headers: {
'Content-type': 'application/json',
Accept: 'image/png',
},
}
)
.then(data => {
console.log(data);
const blob = new Blob([data], {
type: 'image/png',
});
this.FileSaver.saveAs(blob, 'testing.png');
});
}
控制台日志结果如下:
Object {data: "�PNG
↵↵
IHDRRX��iCCPICC Profi…g�x @� @������Z��IEND�B`�", status: 200, config: Object, statusText: "OK", headers: function}
我应该解码object.data
吗?
最佳答案
尝试将 responseType: 'blob'
添加到请求中并忽略创建新的 blob:
function exportReport(_id) {
this.$http
.post(
'/api/report',
{ _id },
{
headers: {
'Content-type': 'application/json',
Accept: 'image/png',
},
responseType: 'blob'
}
)
.then(data => {
console.log(data);
this.FileSaver.saveAs(data.data, 'testing.png');
});
}
关于javascript - 使用客户端 Javascript 从 Node 的 readStream 保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45057553/