javascript - 使用客户端 Javascript 从 Node 的 readStream 保存图像

标签 javascript angularjs node.js blob filesaver.js

我已经在这个问题上苦苦挣扎了一段时间了,需要你们的帮助!我正在尝试简化从我的网站下载报告的过程。对于 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/

相关文章:

javascript - Fabricjs 克隆 Canvas 从矩形中删除小数

angularjs - 分度器返回转发器的值数组

ruby-on-rails - 有人可以给我一个 node.js 应用程序的例子吗

javascript - AngularJS ng-change 和 select 标签的问题

angularjs - 在 AngularJS forEach 中添加延迟

javascript - Protractor 停止工作。你能明白为什么吗?

node.js - 如何保持 Karma 服务器运行,但仅在我手动告诉它之前才运行测试?

javascript - 使用 'this' 选择属性,然后与选定的 HTML 属性进行比较

php - PHP 中的 Javascript 变量值

动态引用函数时的 JavaScript 变量范围