如何将字符串类型从 API 响应转换为图像文件 - ����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001 -

How to convert the string type from an API response to an image file - ����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001 -

我已经使用https://graph.microsoft.com/beta/me/photo/$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: "https://graph.microsoft.com/beta/me/photo/$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.com/package/request#streaming

https://nodejs.org/api/fs.html#fs_class_fs_writestream

原因是默认情况下,request 将对响应数据调用 .toString()。对于二进制数据,例如 RAW JPEG,这不是您想要的。

request 文档中也有解释(尽管含糊不清):

(Note: if you expect binary data, you should set encoding: null.)

这意味着您也可以使用它:

const options = {  
  encoding : null,
  url      : "https://graph.microsoft.com/beta/me/photo/$value",
  method   : 'GET',
  headers  : {
    'Accept'        : 'application/json',
    'Authorization' : `Bearer ${locals.access_token}`,
    'Content-type'  : 'image/jpg',
  }
};

但是,流式处理可能仍然是更好的解决方案,因为它不需要先将整个响应读入内存。

请求是 deprecated。你可以用 axios 做到这一点;

// GET request for remote image in node.js
axios({
  method: 'get',
  url: 'http://example.com/file.jpg',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });