繁体   English   中英

Nodejs 将 base64 用作图像

[英]Nodejs serve base64 as Image

我正在尝试将 base64 字符串作为带有image/png标头的图像提供。 标题设置正确,但没有显示图像,我只能看到一个空白屏幕。 这是代码:

request('someCustomLink', function (error, response, body) {
// someCustomLink gives the base64 string
        var img = new Buffer(body, 'base64');
        res.writeHead(200, {
            'Content-Type': 'image/png',
            'Content-Length': img.length
        });
        res.end(img);         
});

是我为达到此解决方案而遵循的链接。

任何帮助将不胜感激。

编辑这是我的 someCustomLink 的响应标头(它可能有助于理解问题 betr)

Accept-Ranges:bytes
Content-Length:128778
Content-Type:image-jpeg
Date:Thu, 21 Dec 2017 06:03:52 GMT
ETag:"edc04d469779108860478b361b7427d7"
Last-Modified:Mon, 11 Dec 2017 08:54:32 GMT
Server:AmazonS3
x-amz-id-2:QlR39g0vC5CeOo6fdKzX9uFB+uiOtj61c0LKW2rQLcCPWllcKyfbpg93Yido+vZfzMzB3lmhbNQ=
x-amz-request-id:3EC77634D9A05371

这是获取请求

var request = require('request').defaults({ encoding: null });

app.get('/thumb/:thumbLink', function(req, res) {


        request('https://s3.amazonaws.com/my-trybucket/projectImages/'+req.params.thumbLink, function (error, response, body) {
            //console.log('error:', error); // Print the error if one occurred
            //console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            //console.log('body:', body); // Print the HTML for the Google homepage.
            var img = new Buffer(body, 'base64');
            res.writeHead(200, {
                'Content-Type': 'image/png'

            });
            res.end(img);
        });
    });

-谢谢

您收到的响应包含data:image/png;base64, 在创建Buffer之前,您已将其删除。 请参阅下面的示例

request('https://s3.amazonaws.com/my-trybucket/projectImages/e31492f7314837a22a64395eee7cedfd', function(error, response, body) {
    var img = new Buffer(body.split(',')[1], 'base64');
    res.writeHead(200, {
      'Content-Type': 'image/png',
      'Content-Length': img.length 
    });
    res.end(img);
})

在这个特定问题上也停留了很长时间,只是发现发送从 s3 返回的实际数据 Body 实际上足以显示图像。 这是我的实现(在打字稿中):

// a method in my Bucket class

async getObject(key: string) {
    const params = {
      Bucket: this.bucket, //my bucket name set in my constructor
      Key: key,
    };
    return new Promise((resolve, reject) => {
      s3.getObject(params, (err, data) => {
        if (err) reject(err);
        if(data) resolve(data.Body);
      });
    });
  }

// the get request route

app.get(
  "url/:folder/:id",
  async (req: Request, res: Response) => {
    const { folder, id } = req.params;
    const image = (await new Bucket().getObject(`${folder}/${id}`)) as Buffer;
    res.send(image);
  }
);

我在我的服务器上收到错误ECONNRESET 原来res.end()对此负责。 我用res.send()替换了它,传输没有问题。 这是我提供 base64 文件的通用解决方案

async (req: Request, res: Response) => {
  const { id } = req.params;

  //Get the image or file with your own method
  const base64File = await GetBase64File(id)

  const [fileInfo, fileData] = base64File.split(",");
  const contentType = fileInfo.split(";")[0].replace("data:", "");

  res.setHeader("Content-Type", contentType);
  res.setHeader("Content-Length", fileData.length);

  const buffer = Buffer.from(fileData, "base64");
  res.send(buffer);
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM