Himanshu Raj
Himanshu Raj

Reputation: 123

how to upload image on amazon s3 using nodejs and make it public

I am using the following code to upload the image on amazon S3, but it is not public. What else parameter do I need to pass to make it public.

var AWS = require('aws-sdk');
AWS.config.region = 'us-west-2';

var s3bucket = new AWS.S3({params: {Bucket: 'myBucket'}});
s3bucket.createBucket(function() {
var params = {Key: 'myKey', Body: 'Hello!'};
s3bucket.upload(params, function(err, data) {
if (err) {
  console.log("Error uploading data: ", err);
} else {
  console.log("Successfully uploaded data to myBucket/myKey");
}
});
});

Upvotes: 6

Views: 9402

Answers (3)

Siten
Siten

Reputation: 4533

Make resource public when upload data at s3 bucket. I can able to download that link from any where.

Just try it:

var s3bucket = new AWS.S3({
  region: Constant.AWS_S3_REGION
 });
 console.log(filename);
 var params = {
  Key: filename,
  Body: fs.createReadStream(filepath),
  Bucket: Constant.AWS_S3_BUCKET,
  ACL:'public-read-write'
 };
s3bucket.upload(params, cb)

Cheers...!!!!

Upvotes: 9

Himanshu Raj
Himanshu Raj

Reputation: 123

Sorry My earlier code was

var express = require('express');

var app = express();

var bodyParser = require('body-parser');

app.use(bodyParser.json()); // support json encoded bodies

app.use(bodyParser.urlencoded({ extended: true })); 

var multipart = require('connect-multiparty');

var multipartMiddleware = multipart();

var fs = require('fs'),
    S3FS = require('s3fs'),
    s3fsImpl = new S3FS('****', {
    accessKeyId: '***',
    secretAccessKey: '**********'
});

// Create our bucket if it doesn't exist
s3fsImpl.create();

app.post('/api',multipartMiddleware, function (req, res) {

res.send(req.body, req.files);

var file = req.files.file;

var stream = fs.createReadStream(file.path);

return s3fsImpl.writeFile(file.originalFilename, stream).then(function () {

    fs.unlink(file.path, function (err) {
        if (err) {
            console.error(err);
        }
    });
    res.status(200).end();
});
});

Upvotes: 0

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

For making data public in your bucket, convert following :

var params = {Key: 'myKey', Body: 'Hello!'};

To following:

var params = {Key: 'myKey', Body: 'Hello!', ACL: 'public-read'};

For better understanding follow This Good Tutorial

Happy Helping!

Upvotes: 1

Related Questions