Luiz Alves
Luiz Alves

Reputation: 2645

Update an image into AWS S3 with nodejs

I am using node to save an image into aws s3 storage with aws-sdk and multer midlleware.

I have a photo of a user and I am using a fixed name as key to object in aws S3.

When the user change the photo, I save it into aws s3 again with the same key.

My problem is that the photo in AWS is never updated.

I also tried to delete the object, before update it, but no look.

If I add a unique key to photo all works well.

Is possible update the photo and continues using the same key?

const storageS3 = multerS3({
  s3: s3, //new aws.S3(),
  bucket: process.env.BUCKET_NAME,
  contentType: multerS3.AUTO_CONTENT_TYPE,
  acl: "public-read",
  key: async (req, file, cb) => {
    const fileName = `${req.data.account_id}/empresas/empresa-${req.params.id}/profile/profile` +
      path.extname(file.originalname);
    cb(null, fileName);
  }
});

const uploadProfileS3 = multer({
  storage: storageS3,
  limits: { fileSize: MAX_SIZE },
  fileFilter: function(req, file, cb) {
    checkFileType(file, cb);
  },
}).single("file");

Upvotes: 2

Views: 2756

Answers (1)

Tamás Sallai
Tamás Sallai

Reputation: 3365

Two things that can cause this. First, S3 is eventually consistent (https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyModel) so that if you update an object a subsequent GET might get the old object. I couldn't find any guarantees how much time this "eventual" consistency might take, but I can imagine if a user uploads a new avatar it won't update for a few seconds.

The second is browser caching. If the original image is still cached then a request to the same URL won't even reach S3 but used the local cache.

If you are storing user avatar images I suggest you store the current image's name in the database and use a fully random name for each upload. This way you can get around any cache issues and also you'll benefit from S3's read-after-write consistency.

Upvotes: 1

Related Questions