javascript - Nodejs 将 base64 作为图像

标签 javascript node.js

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

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);         
});

this是我找到此解决方案所遵循的链接。

我们将不胜感激。

编辑 这是我的 someCustomLink 的响应 header (它可能有助于更好地理解问题)

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);
})

关于javascript - Nodejs 将 base64 作为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47918376/

相关文章:

javascript - 如何使用 JSON 检索 OpenWeatherMap 数据?

node.js - Passport 本地策略和 cURL

node.js - 单击电子邮件中的网址时,浏览器中不显示路线

node.js - pm2 创建了一个 "source"目录并将我的所有文件复制到其中,为什么?

javascript - 如果鼠标悬停 Div 等于 False - JQuery/Javascript

javascript - 如何将位于 View 中的 Javascript 值传递给 C# 方法

javascript - 加载和连接 js/jsx 文件

javascript 改变 ruby​​ 变量

javascript - 如何设置 webpack 以支持 Node 中的 ES6 模块

node.js - 我的 npm 不工作