Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS AWS S3 file upload. How to get public URL response

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");         }     }); 
like image 223
Jack Wild Avatar asked Jun 10 '15 17:06

Jack Wild


People also ask

How do I get my S3 upload URL?

You can get the resource URL either by calling getResourceUrl or getUrl . AmazonS3Client s3Client = (AmazonS3Client)AmazonS3ClientBuilder. defaultClient(); s3Client. putObject(new PutObjectRequest("your-bucket", "some-path/some-key.

How do I find my public S3 bucket URL?

Get an S3 Object's URL #Navigate to the AWS S3 console and click on your bucket's name. Use the search input to find the object if necessary. Click on the checkbox next to the object's name. Click on the Copy URL button.

Is S3 URL public?

Amazon Web Services (AWS) S3 objects are private by default. Only the object owner has permission to access these objects. Optionally we can set bucket policy to whitelist some accounts or URLs to access the objects of our S3 bucket.


1 Answers

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

like image 73
Birju Shah Avatar answered Sep 28 '22 02:09

Birju Shah