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.

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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) {...}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.