如何将字符串类型从API响应转换为图像文件
我使用了/ $ value API来获取outlook用户的个人资料图片。我得到了一个关于在rest-client中运行上述API的图像。 API的内容类型是“image / jpg”
但是,在Node.js中,API的响应如下:
����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000�\u0000\u0005\u0005\u0005\u0005\u0005\u0005\u0006\u0006\u0006\u0006\b\t\b\t\b\f\u000b\n\n\u000b\f\u0012\r\u000e\r\u000e\r\u0012\u001b\u0011\u0014\u0011\u0011\u0014\u0011\u001b\u0018\u001d\u0018\u0016\u0018\u001d\u0018+"\u001e\u001e"+2*(*2<66<LHLdd�\u
我用'fs'来创建一个图像文件。代码如下:
const options = {
url: "/$value",
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${locals.access_token}`,
'Content-type': 'image/jpg',
}
};
request(options, (err, res, body) => {
if(err){
reject(err);
}
console.log(res);
const fs = require('fs');
const data = new Buffer(body).toString("base64");
// const data = new Buffer(body);
fs.writeFileSync('profile.jpg', data, (err) => {
if (err) {
console.log("There was an error writing the image")
}
else {
console.log("The file is written successfully");
}
});
});
文件写入成功,但生成的.jpg
图像文件已损坏。我无法打开图像。图像文件的输出如下:
77+977+977+977+9ABBKRklGAAEBAAABAAEAAO+/ve
回答如下:
你可以通过像这样流式传输响应来做到这一点,
request(options,(err,res,body)=>{
console.log('Done!');
}).pipe(fs.createWriteStream('./profile.jpg'));
https://www.npmjs/package/request#streaming
https://nodejs/api/fs.html#fs_class_fs_writestream
如何将字符串类型从API响应转换为图像文件
我使用了/ $ value API来获取outlook用户的个人资料图片。我得到了一个关于在rest-client中运行上述API的图像。 API的内容类型是“image / jpg”
但是,在Node.js中,API的响应如下:
����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000�\u0000\u0005\u0005\u0005\u0005\u0005\u0005\u0006\u0006\u0006\u0006\b\t\b\t\b\f\u000b\n\n\u000b\f\u0012\r\u000e\r\u000e\r\u0012\u001b\u0011\u0014\u0011\u0011\u0014\u0011\u001b\u0018\u001d\u0018\u0016\u0018\u001d\u0018+"\u001e\u001e"+2*(*2<66<LHLdd�\u
我用'fs'来创建一个图像文件。代码如下:
const options = {
url: "/$value",
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${locals.access_token}`,
'Content-type': 'image/jpg',
}
};
request(options, (err, res, body) => {
if(err){
reject(err);
}
console.log(res);
const fs = require('fs');
const data = new Buffer(body).toString("base64");
// const data = new Buffer(body);
fs.writeFileSync('profile.jpg', data, (err) => {
if (err) {
console.log("There was an error writing the image")
}
else {
console.log("The file is written successfully");
}
});
});
文件写入成功,但生成的.jpg
图像文件已损坏。我无法打开图像。图像文件的输出如下:
77+977+977+977+9ABBKRklGAAEBAAABAAEAAO+/ve
回答如下:
你可以通过像这样流式传输响应来做到这一点,
request(options,(err,res,body)=>{
console.log('Done!');
}).pipe(fs.createWriteStream('./profile.jpg'));
https://www.npmjs/package/request#streaming
https://nodejs/api/fs.html#fs_class_fs_writestream