37

I'm uploading a file to Amazon S3 using the Node SDK.

The file uploads are working fine, but I want to get the public url of the file to send back to the client.

At the moment the response I get is:

Successfully uploaded data { ETag: '"957cd1a335adf5b4000a5101ec1f52bf"' }

Here is my code. I'm using a Node Express server, and Multer to handle uploads.

app.use(multer({ // https://github.com/expressjs/multer
      dest: './public/uploads/', 
      limits : { fileSize:100000 },
      rename: function (fieldname, filename) {
        var time = new Date().getTime();
        return filename.replace(/\W+/g, '-').toLowerCase() + time;
      },
      onFileUploadData: function (file, data, req, res) {
        // file : { fieldname, originalname, name, encoding, mimetype, path, extension, size, truncated, buffer }
        var params = {
          Bucket: creds.awsBucket,
          Key: file.name,
          Body: data,
          ACL: 'public-read'
        };

        var s3 = new aws.S3()
        s3.putObject(params, function (perr, pres) {
          if (perr) {
            console.log("Error uploading data: ", perr);
          } else {
            console.log("Successfully uploaded data", pres);
          }
        });
      }
    }));

    app.post('/upload-image', function(req, res){
        if(req.files.file === undefined){
            res.send("error, no file chosen");
        }
    });
Jack Wild
  • 2,072
  • 6
  • 27
  • 39
  • how you made this to work, I get 'Error initializing middleware TypeError: app.use() requires middleware functions' message – someUser Apr 11 '16 at 15:25

1 Answers1

47

Use upload instead of putObject. It will return public url in Location key

Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
Birju Shah
  • 1,220
  • 9
  • 18
  • 5
    Weird. `putObject(...).promise()` works fine, but `upload(...).promise()` is undefined. Why did they do that. – Richard Jul 22 '16 at 12:37
  • 1
    @Richard does ` putObject(...).promise()` return the public url in a location key as I can't find it myself. Here's some info from July 2016: Promises are currently only supported on operations that return a Request object. Since s3.upload is a custom function that returns an instance of ManagedUpload rather than Request, promises are not currently supported for that operation [reference](https://github.com/aws/aws-sdk-js/issues/1076#issuecomment-235941953) – Marklar Jul 25 '17 at 04:08