Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get uploaded object URL with Javascript 'aws-sdk' v3

Currently, we are using aws-sdk v2, and extracting uploaded file URL in this way

  const res = await S3Client
    .upload({
      Body: body,
      Bucket: bucket,
      Key: key,
      ContentType: contentType,
    })
    .promise();

  return res.Location;

Now we have to upgrade to aws-sdk v3, and the new way to upload files looks like this

const command = new PutObjectCommand({
  Body: body,
  Bucket: bucket,
  Key: key,
  ContentType: contentType,
});

const res = await S3Client.send(command);

Unfortunately, res object doesn't contain Location property now.

getSignedUrl SDK function doesn't look suitable because it just generates a URL with an expiration date (probably it can be set to some extra huge duration, but anyway, we still need to have a possibility to analyze the URL path)

Building the URL manually does not look like a good idea and a stable solution to me.

like image 848
humkins Avatar asked Mar 13 '26 20:03

humkins


1 Answers

Answering myself: I don't know whether a better solution exists, but here is how I do it

const command = new PutObjectCommand({
  Body: body,
  Bucket: bucket,
  Key: key,
  ContentType: contentType,
});

const [res, region] = await Promise.all([
  s3Client.send(command),
  s3Client.config.region(),
]);

const url = `https://${bucket}.s3.${region}.amazonaws.com/${key}`
like image 92
humkins Avatar answered Mar 15 '26 17:03

humkins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!