2014-01-07 211 views
1

替换文件不能替换文件中的Amazon S3桶不能在Amazon S3的桶

当我要上传图片到amazon s3桶它显示错误,如下面 An item with the same key has already been added

我上传了一个图片文件,我想在需要时替换那张图片。但它不允许。

我该如何解决?

我使用C#

using (s3Client = Amazon.AWSClientFactory.CreateAmazonS3Client("key", "secret key", Amazon.RegionEndpoint.USWest2)) 
      { 
       var stream2 = new System.IO.MemoryStream(); 
       bitmap.Save(stream2, ImageFormat.Jpeg); 

       stream2.Position = 0; 
       PutObjectRequest request2 = new PutObjectRequest(); 
       request2.InputStream = stream2; 
       request2.BucketName = "ezcimassets"; 
       request2.CannedACL = S3CannedACL.PublicRead; 
       fileName = webpage + ".jpeg"; 
       //fileName = Guid.NewGuid() + webpage + ".jpeg";) 
       request2.Key = "WebThumbnails/" + fileName; 

       Amazon.S3.Model.PutObjectResponse response = s3Client.PutObject(request2); 

      } 

在此先感谢

+0

你能发布amazon s3的实际响应吗?亚马逊并不阻止更新现有对象。它会覆盖put对象请求API。 首先请确认您的代码正在执行上面的代码部分,我认为在执行putobject的上述代码之前,您的应用程序正在通过GET或HEAD对象请求api检查现有的代码。 –

+1

我可以找到解决方案,该行必须编辑为request2.CannedACL = S3CannedACL.PublicReadWrite –

回答

1

此行必须改为

request2.CannedACL = S3CannedACL.PublicReadWrite

+0

如果我只想要经过身份验证的用户读取文件,该怎么办? – gkb

0

您可以检查是否与键的对象已经存在,如果是这样删除它:

public bool Exists(string fileKey, string bucketName) 
{ 
     try 
     { 
      response = _s3Client.GetObjectMetadata(new GetObjectMetadataRequest() 
       .WithBucketName(bucketName) 
       .WithKey(key)); 

      return true; 
     } 

     catch (Amazon.S3.AmazonS3Exception ex) 
     { 
      if (ex.StatusCode == System.Net.HttpStatusCode.NotFound) 
       return false; 

      //status wasn't not found, so throw the exception 
      throw; 
     } 
} 

public void Delete(string fileKey, string bucketName) 
{ 
    DeleteObjectRequest request = new DeleteObjectRequest(); 
    request.BucketName = bucketName; 
    request.Key  = fileKey; 
    client.DeleteObject(request); 
}