使用客户端 Javascript 保存 Node 的 readStream 中的图像



我已经为此苦苦挣扎了一段时间,需要你们的帮助!我正在尝试简化从我的网站下载报告的过程。对于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');
}
});
});

现在,如果我与邮递员或其他一些 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');
});
}

最新更新