0

I'm trying to download an image from my server using request. I've managed to download something but i get more data than the image.

function _download(uri, save_as, destination) {
    let options = {
        uri: uri,
        timeout: 100000,
        followAllRedirects: true
    };
    return new Promise(( _resolve,_reject) => {
        let ext, filename, bar, total, downloaded, req;
        req = request(options).on('response', (resp) => {
            if (resp.statusCode === 200){
                ext = _getFileType(resp.headers['content-type']);
                filename = destination+'/'+save_as+ext;
                var stream = fs.createWriteStream(filename)
                resp.pipe(stream).on('error',function(err){
                    _reject(err);
                }).on('finish',function(){
                    _resolve(filename);
                });
            } else {
                _reject("unable to download image %s",uri);
            }
        }).on('error', function(err) {
            console.log(err)
            _reject(err);
        })
    });
}

My original url is in form of https://www.test.com/image/original/12345, my server than redirects with a 301 status to my s3 bucket where image is stored.
Unfortunately due to the url of the image i have to wait that for the response header content type to determinate what kind of image it's and use it to pipe the image.
Everything works quite as expected... but i get more data than what is stored in s3.
Does anyone have any suggestion ?

Tiziano
  • 316
  • 1
  • 4
  • 17

1 Answers1

2

please refer to the link below

var fs = require('fs'),
request = require('request');

var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);

request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};

download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
console.log('done');
});

please visit this link

And this link also