我在Node.js上,使用Dropbox的HTTP API中的“下载”端点。我返回的数据是原始的二进制数据。如何使用fs.writeFile将映像保存到文件系统?我尝试将数据读取到缓冲区并将缓冲区传递到fs.writeFile,但确实得到了jpg文件,但是该文件无效并且无法由Mac的照片查看器打开。
这是我的代码,我从发出的请求中获取有效数据,我只是不知道它的编码或格式。
// make a request to dropbox http api endpoint: "download"
axios(options)
.then(function (response) {
// read the data to a buffer
var buffer = Buffer.from(response.data, "binary");
// create an image from the buffer
fs.writeFile('path/image.jpg', buffer, function (err) {
if (err) console.error(err);
res.sendFile('path/image.jpg');
});
})
.catch(function (err) {
console.error(err);
});
此问题类似,但以base64字符串开头:Writing binary data using node.js fs.writeFile to create an image file
base64上的另一个:NodeJS: Saving a base64-encoded image to disk