2013-11-09 2 views
2

Amazon S3을 사용하여 구현 작업을하고 있습니다. Amazon C# SDK을 사용하고 putObject 메소드를 사용하여 생성 된 ZIP 파일을 업로드하려고합니다. 나는 잘하고 작업 MemoryStream을을 생성MD5 해시로 스트림을 업로드하면 "지정한 콘텐츠 -MD5가 유효하지 않습니다."

{Amazon.S3.AmazonS3Exception: The Content-MD5 you specified was invalid 

, 나는 오류없이 아마존 S3에 업로드 할 수 있습니다 : 내가 파일을 업로드 할 때

, 나는 다음과 같은 오류가 발생합니다. 그러나 다음 줄을 제공하면 문제가 발생합니다.

request.MD5Digest = md5; 

올바른 방법으로 MD5를 증명합니까? 내 MD5 세대가 맞습니까? 아니면 다른 문제가 있습니까? 내 업로드 코드에

요구 사항을 :

public void UploadFile(string bucketName, Stream uploadFileStream, string remoteFileName, string md5) 
     { 
      using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKeyID, secretAccessKeyID, config)) 
      { 
       try 
       { 
        StringBuilder stringResp = new StringBuilder(); 

        PutObjectRequest request = new PutObjectRequest(); 
        // request.MD5Digest = md5; 
        request.BucketName = bucketName; 
        request.InputStream = uploadFileStream; 
        request.Key = remoteFileName; 
        request.MD5Digest = md5; 

        using (S3Response response = client.PutObject(request)) 
        { 
         WebHeaderCollection headers = response.Headers; 
         foreach (string key in headers.Keys) 
         { 
          stringResp.AppendLine(string.Format("Key: {0}, value: {1}", key,headers.Get(key).ToString())); 
          //log headers ("Response Header: {0}, Value: {1}", key, headers.Get(key)); 
         } 
        } 
       } 
       catch (AmazonS3Exception amazonS3Exception) 
       { 
        if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) 
        { 
         //log exception - ("Please check the provided AWS Credentials."); 
        } 
        else 
        { 
         //log exception -("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message); 
        } 
       } 
      } 
     } 

전체 방법 :

Once the Zip file has been created and you have calculated an MD5 sum value of that file, you should 
transfer the file to the AWS S3 bucket identified in the S3Access XML. 
Transfer the file using the AmazonS3, PutObjectRequest and TransferManagerclasses. 
Ensure the following meta data attributes are included via adding an ObjectMetaDataclass instance to the 
PutObjectRequest: 
• MD5Sum (via setContentMD5) 
• Mime ContentType (setContentType) 

내 업로드 코드 client.PutObject()가 오류를 제공

내 처리 방법 (전체 플로우보기).

public void Process(List<Order> order) 
    { 
     var zipName = UserName + "-" + DateTime.Now.ToString("yy-MM-dd-hhmmss") + ".zip"; 
     var zipPath = HttpContext.Current.Server.MapPath("~/Content/zip-fulfillment/" + zipName); 

     CreateZip(order, zipPath); 


     var s3 = GetS3Access(); 

     var amazonService = new AmazonS3Service(s3.keyid, s3.secretkey, "s3.amazonaws.com"); 
     var fileStream = new MemoryStream(HelperMethods.GetBytes(zipPath)); 
     var md5val = HelperMethods.GetMD5HashFromStream(fileStream); 
     fileStream.Position = 0; 
     amazonService.UploadFile(s3.bucket, fileStream, zipName, md5val); 

     var sqsDoc = DeliveryXml(md5val, s3.bucket, "Test job"); 

     amazonService.SendSQSMessage(sqsDoc.ToString(), s3.postqueue); 
    } 

MD5 해싱 방법 : 생산 코드보다 더 많은 의사 코드는 코드의 현재 상태에 대한 죄송합니다이 방법은 내 MemoryStream을에서 MD5 해시를 만드는 데 사용됩니다

:

public static string GetMD5HashFromStream(Stream stream) 
    { 

     MD5 md5 = new MD5CryptoServiceProvider(); 
     byte[] retVal = md5.ComputeHash(stream); 

     StringBuilder sb = new StringBuilder(); 
     for (int i = 0; i < retVal.Length; i++) 
     { 
      sb.Append(retVal[i].ToString("x2")); 
     } 
     return sb.ToString(); 
    } 

편집 :

그냥 추가 fileStream.Positi 전체 방법에서 on = 0. 그래도 정확히 똑같은 문제.

답변

7

스트림의 해시를 계산 한 후 스트림이 데이터의 에 남겨져있는 것으로 의심됩니다. 그래서 다른 데이터가 나중에 읽히면 아무 데이터도 없을 것입니다. 당신이 다시 읽을 수 있도록 스트림을 "되감기"합니다 GetMD5HashFromStream

fileStream.Position = 0; 

이로 호출 한 후이 추가보십시오.

편집 : 위의 내용은 문제 일 뿐이지 만 문제는 아닙니다.

Content-MD5: The base64-encoded 128-bit MD5 digest of the message

참고 "base64 인코딩"부분 :하지만 documentation 상태 - 현재, 당신은 MD5 해시의 진수 표현을 추가하고 있습니다.MD5 코드를 다음과 같이 변경하려고합니다.

public static string GetMD5HashFromStream(Stream stream) 
{ 
    using (MD5 md5 = MD5.Create()) 
    { 
     byte[] hash = md5.ComputeHash(stream); 
     return Convert.ToBase64String(hash); 
    } 
} 
+0

방금 ​​시도했지만 문제가 해결되지 않았습니다. 흠, 제안에 대해서도 고마워요. - 문제 일 수도 있습니다. –

+0

@LarsHoldgaard : 내 편집을 참조하십시오. 다행히도 그것을 정렬합니다 ... –

+0

예! 고마워요 (다시) ... 정말 도움이 : Thnx –

관련 문제