简体   繁体   中英

AWS S3 No Such Key Exist Error

My client has a number of images stored on AWS-S3. I am able to get those images. The issue is earlier they used to store the images with numeric key and now they use GUID. For example the key can be either 12345/MyFile.jpg or ASDF-XYZ/MyFile.jpg and they don't store the key. The only thing stored in the DB is userId and fileName. So I only have 12345/MyFile.jpg in the database. When I try to use the code below:

var params = {
    Bucket: bucketName,
    Key: "12345/MyFile.jpg",
    IfMatch: eTag,
    };

var fileStream = s3.getObject(params).createReadStream();

This works only if it exist. If the file does not exist it throws exception "No such key exist". So the file is existing under GUID key.

var params = {
    Bucket: bucketName,
    Key: "ASDF-XYZ/MyFile.jpg",
    IfMatch: eTag,
    };

var fileStream = s3.getObject(params).createReadStream();

This works. So, is there any way I can check if the file exist in numeric directory(for clarification's sake) the code reads from it otherwise it should get the image from GUID directory? I have tried try-catch but that doesn't work.

The general practice is to use headObject to check for the metadata in S3, which you can use to find out if that errors or not, and if so, return the old style.

The following codeblog presumes you try the numeric directory first and fallback to the GUID.

s3.headObject(numericDirectoryParams).on('success', function(response) {
  return s3.getObject(numericDirectoryParams).createReadStream();
}).on('error',function(error){
  // File did not exist in numeric directory, get in GUID
  return s3.getObject(GUIDparams).createReadStream();
}).send();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM