How to upload a remote image in Node/request?
Asked Answered
M

1

2

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.

Morlee answered 17/10, 2015 at 1:24 Comment(0)
B
1

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);
}
Buskin answered 17/10, 2015 at 1:49 Comment(2)
Thx - that works quite well - out of curiosity, would it be possible to do the same without creating any files? Or is that just a necessary step?Morlee
Glad I could help. If this answers your question, then please accept it as the right answer. – This is just an another way to use request, we're streaming in the response body and saving. A typical use is when you scrape a page then collect the data to do something with it. So it looks like: request(url, function(error, response, body) {...}Buskin

© 2022 - 2024 — McMap. All rights reserved.