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

问题描述 投票:9回答:2

我使用了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
javascript node.js microsoft-graph fs
2个回答
3
投票

你可以通过像这样流式传输响应来做到这一点,

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


0
投票

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

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

(注意:如果您需要二进制数据,则应设置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',
  }
};

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

© www.soinside.com 2019 - 2024. All rights reserved.