Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save image from URL to S3 in node.js

I would like to be able to save images from URL to S3. I've been able to do something similar by allowing users to upload profile pictures by using this code (docs here):

uploadUserImage: function(req, res) {
    var userName = req.params.username;
    var fname = userName + ".jpg";
    var userAvatar = "https://.......;

    req.file('image').upload({
      adapter: require('skipper-s3'),
      key:'xxxxxxxxxxxx',
      secret:'xxxxxxxxxx',
      region: "xxxxxx",
      bucket: 'xxxxxxx',
      headers: {
        ACL: 'public-read'
      },
      saveAs: "user-images/"+fname
    }, function whenDone(err, uploadedFiles) {

Is there anyway I could modify this code so I can save images from a URL/ link?

I've been trying to do something like this but I can't figure out how it would work.

var request = require('request');
function(person, next) {

      request({
          url:person.image,
          encoding:null
      }, function(err, res, reqBody) {
          if (err) {
              console.log(err);
          } else {
              console.log(reqBody);
              console.log(res);
          }
      reqBody.upload({
       adapter: require('skipper-s3'),
       key:'xxxxxxxxxxxx',
       secret:'xxxxxxxxxx',
       region: "xxxxxx",
       bucket: 'xxxxxxx',
       headers: {
        ACL: 'public-read'
      },
        saveAs: "user-images/"+person.id+".jpeg"
      }, function whenDone(err, uploadedFiles) {
            if(err) {
                return next(err);
            } else {
                person.image = "https:........";
                return next(null, person);
            }
        });
    });

  },
like image 672
BryanXYZ Avatar asked Jun 01 '26 07:06

BryanXYZ


1 Answers

Not possible. You have to download the file yourself, then upload it.

There is only one way to persuade S3 to fetch a file for you and write it to your bucket, and that is when the file is already in S3. S3 can copy a file by fetching from... itself. But it will not go fetch anything http... on your behalf.

like image 176
Michael - sqlbot Avatar answered Jun 04 '26 05:06

Michael - sqlbot