2014-01-07 151 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); 
}