Search code examples
node.jsmultipartform-datanode-request

How to upload a remote image in Node/request?


I would like to upload a remote image to my own server using Node and the request module. I've figure out how to upload local images using the following code:

var options = {
    url: 'https://myownserver.com/images'
};
var req = request.post(options , function optionalCallback(err, httpResponse, body) {
  console.log('Upload successful!  Server responded with:', body);
});

var form = req.form();
form.append('file', fs.createReadStream(__dirname + '/testimg.png'));

What modifications would I need to make to this code to be able to upload a remote image? This is the image I have been working with: https://www.filepicker.io/api/file/egqDUkbMQlmz7lqKYTZO

I've tried using fs.createReadStream on the remote URL, but was unsuccessful. If possible, I would prefer not having to save the image locally before uploading it to my own server.


Solution

  • This is a piece of code I'm using with a scraper. I'm using the callback here so I can use this as the location when saving to my model. I'm putting the location of your image below, but in my code I use req.body.image.

    var downloadURI = function(url, filename, callback) {
    
      request(url)
        .pipe(fs.createWriteStream(filename))
        .on('close', function() {
          callback(filename);
        });
    };
    
    downloadURI('https://myownserver.com/images', __dirname + '/testimg.png', function(filename) {
     console.log(done);
    }