阅读背景:

AWS S3没有此类密钥存在错误

来源:互联网 

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:

我的客户端有许多存储在AWS-S3上的图像。我能够得到那些图像。问题是他们过去常常使用数字键存储图像,现在他们使用GUID。例如,密钥可以是12345 / MyFile.jpg或ASDF-XYZ / MyFile.jpg,并且它们不存储密钥。存储在DB中的唯一内容是userId和fileName。所以我在数据库中只有12345 / MyFile.jpg。当我尝试使用以下代码时:

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.

这只有在存在时才有效。如果该文件不存在,则抛出异常“不存在此类密钥”。因此该文件存在于GUID密钥下。

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.

这很有效。那么,有什么方法可以检查文件是否存在于数字目录中(为了澄清)代码从中读取,否则它应该从GUID目录中获取图像?我尝试过try-catch,但这不起作用。

1 个解决方案

#1


1  

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.

一般做法是使用headObject检查S3中的元数据,您可以使用它来查明是否存在错误,如果是,则返回旧样式。

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

以下代码博客假设您首先尝试数字目录并回退到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();

分享到: