AWS S3 PutObjectAsync ETag与MD5不匹配

时间:2019-07-11 19:04:55

标签: c# amazon-s3 md5

我正在尝试将文件上传到S3(PutObjectAsync),然后检查它是否在那里。

我发现我生成的MD5哈希与返回的ETag不匹配,什么是验证文件的正确方法?

                using (var fileDataStream = new MemoryStream())
                {
                    using (var md5 = MD5.Create())
                    {
                        file.CopyTo(fileDataStream);

                        var hash = md5.ComputeHash(fileDataStream.ToArray());
                        var hashAsString = Convert.ToBase64String(hash);

                        var request = new PutObjectRequest
                        {
                            CannedACL = S3CannedACL.PublicRead,
                            InputStream = fileDataStream,
                            BucketName = _optionsAws.Value.MediaBucketName,
                            Key = s3FileName
                        };

                        var result = await _s3Client.PutObjectAsync(request);

                        if (result.ETag != hashAsString)
                        {
                            ret.isSuccess = false;
                            ret.errorMessage = "Non matching hash";
                        }
                        else
                        {
                            ret.isSuccess = true;
                        }
                    }
                }

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。这样解决了,尽管我确实必须从ETag响应中删去'“'(双引号)字符,但MD5哈希与S3上传中的ETag匹配得很好。分段上传文件。

     public static string CalculateMD5Hash(byte[] bytes)
        {
            MD5 md5 = MD5.Create();
            byte[] hash = md5.ComputeHash(bytes);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }
            return sb.ToString();
        }