0

I am trying to generate presigned url for my s3 bucket. After that when i copy paste the generated url in browser i get this error

<Error>
<Code>NoSuchKey</Code>
<Message>The specified key does not exist.</Message>
<Key>xx</Key>
<RequestId>xx</RequestId>
<HostId>xx</HostId>
</Error>

My code:

const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');
const dotenv = require('dotenv');
dotenv.config();

let region = 'us-east-1';

aws.config.update({
  secretAccessKey: process.env.SECRET_ACCESS_KEY,
  accessKeyId: process.env.ACCESS_KEY_ID,
  region: region,
  signatureVersion: 'v4'
});

var s3 = new aws.S3({
  region:region
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(new Error('Invalid file type, only JPEG and PNG is allowed!'), false);
  }
};

let bucketName = 'somebucketname123';

const signedUrlExpireSeconds = 60 * 5;

const url = s3.getSignedUrl('getObject', {
  Bucket: bucketName,
  Key: process.env.SECRET_ACCESS_KEY,
  Expires: signedUrlExpireSeconds
})

console.log('url', url);

const upload = multer({
  fileFilter: fileFilter,
  storage: multerS3({
    acl: 'public-read',
    s3,
    bucket: bucketName,
    key: function(req, file, cb) {       
      req.file = file.originalname;
      cb(null, file.originalname);
    }
  })
});



module.exports = upload;

i am new to aws and i don't know what i am making wrong here...

What should happen when i paste the new generated presigned url in the browser ? Is this preigned url generated for some specific file ? If it is where in my code should i tell, for which file name in my s3 bucket

sdsd
  • 447
  • 3
  • 20

1 Answers1

4

KEY in bucketParms should be the key of the s3 object.

Signed Url for downloading an object from S3

Bucket: test-events ObjectKey: myfolder/test.json

const bucketParms = {
  Bucket: "test-events",
  Key: "myfolder/test.json",
  Expires: 60,
};

For Downloading:

s3.getSignedUrl("getObject", bucketParms, (error, url) => {
  if (error) console.log("error", error);
  if (url) console.log("url", url);
});

for Uploading the object to S3 , we will still need to specify Bucket and Key to which we want to upload.

s3.getSignedUrl("putObject", bucketParms, (error, url) => {
  if (error) console.log("error", error);
  if (url) console.log("url", url);
});

For using this URL for uploading, we can do a curl or postman

curl --location --request PUT 'https://test-events.s3.amazonaws.com/98..?X....' \
--header 'Content-Type: image/png' \
--data-binary '/Users/user/image/path'

or From PostMan PUT/POST with Body binary and selecting the file. Object will be uploaded to myfolder/test.json (name of the file selected doesn't matter)

Balu Vyamajala
  • 9,287
  • 1
  • 20
  • 42