Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node AWS S3 get object metadata?

I'm trying to store a user's uploaded files in S3 using presigned URLs. This works fine, but I'm using UUIDs as the filename to avoid conflicts. I need to be able to save the file's original filename, so I'm passing it as metadata in the signed upload URL:

const url = await s3.getSignedUrlPromise('putObject', {
  Bucket: UPLOAD_BUCKET,
  Key: key,
  Expires: AWS_UPLOAD_EXPIRATION / 1000,
  ContentType: contentType,
  Metadata: {
    filename: originalFilename
  },
});

This also appears to work fine (the metadata is showing in the AWS console). How can I access this metadata? When the client needs to display one of these images, they request a presigned download URL from the server which is generated like this:

const url = await s3.getSignedUrlPromise('getObject', {
  Bucket: UPLOAD_BUCKET,
  Key: key,
  Expires: AWS_DOWNLOAD_EXPIRATION / 1000,
});

This URL doesn't appear to include the metadata, and the return value of getSignedUrlPromise is a string, so there doesn't seem to be any room for anything other than the URL itself. I assumed there would be an S3 method for fetching just the metadata, but as far as I can tell it doesn't exist (or has an unintuitive name). This is especially confusing considering the getObjectTagging and getObjectLegalHold methods exist. How can I access metadata through a presigned URL? If that's not possible, how can I fetch the metadata using the AWS SDK? If that's not possible, I must be misunderstanding the point of metadata.

like image 937
SimpleJ Avatar asked Jan 02 '20 22:01

SimpleJ


1 Answers

You cannot fetch metadata using URL, but you can use s3.headObject method:

const config = new AWS.Config({
      accessKeyId: 'your acessKey',
      secretAccessKey: 'your secret',
      region: 'your region',
    });
const s3 = new AWS.S3(config);

const params = {
  Bucket: 'your bucket',
  Key: 'your assetKey'
}
const metaData = await s3.headObject(params).promise();

Documentation

like image 142
Aleksandr Kuharenko Avatar answered Sep 30 '22 21:09

Aleksandr Kuharenko