将图像写入文件,通过Node中的HTTP请求接收

时间:2016-09-02 07:14:45

标签: javascript http express png fs

我确定我错过了一些明显的东西,但问题的关键是我从Mapbox调用中收到一个PNG,目的是将其写入文件系统并将其提供给客户端。我已成功转发呼叫,收到原始数据的响应并写入文件。问题是,无论我采取什么样的路径,我的文件都会被截断,而且我已经用尽了我找到的避开主题的答案。我已经将原始响应转储到了日志中,而且它很强大,但我制作的任何文件往往都是一大块不可读的数据。

这是我目前为文件制作所获得的代码。经过几次失败和相对无果的迭代之后,我尝试了这个缓冲移动作为最后的沟渠。任何帮助将不胜感激。

module.exports = function(req, res, cb) {
    var cartography = function() {
        return https.get({
            hostname: 'api.mapbox.com',
            path: '/v4/mapbox.wheatpaste/' + req.body[0] + ',' + req.body[1] + ',6/750x350.png?access_token=' + process.env.MAPBOX_API
        }, function(res) {
            var body = '';
            res.on('data', function(chunk) {
                body += chunk;
            });
            res.on('end', function() {
                var mapPath = 'map' + req.body[0] + req.body[1] + '.png';
                var map = new Buffer(body, 'base64');
                fs.writeFile(__dirname + '/client/images/maps/' + mapPath, map, 'base64', function(err) {
                    if (err) throw err;
                    cb(mapPath);
                })
            })
        });
    };
    cartography();
};

1 个答案:

答案 0 :(得分:0)

可以在更紧凑的子程序中重写代码:

    const fs = require('fs');
    const https = require('https');

    https.get(url, (response)=> { //request itself
        if(response) {
            let imageName = 'image.png'; // for this purpose I usually use crypto
            response.pipe( //pipe response to a write stream (file)
                fs.createWriteStream( //create write stream
                    './public/' + imageName //create a file with name image.png
                )
            );
            return imageName; //if public folder is set as default in app.js
        } else {
            return false;
        }
    })

您可以从url获取原始名称和扩展名,但使用crypto生成新名称更安全,并获取文件扩展名,就像我从url或read-chunk和文件类型模块所说的那样。