[英]How to set md5 to a file while uploading to amazon s3
I am using amazon s3 android low level sdk to upload a file and want to set md5 checksum to upload data. 我正在使用Amazon s3 android低级sdk上传文件,并希望将md5校验和设置为上传数据。
1)Following is the code to create credentials: 1)以下是创建凭据的代码:
BasicAWSCredentials lAwsCredentials = new BasicAWSCredentials(
Constants.ACCESS_KEY_ID, Constants.SECRET_KEY);
AmazonS3Client lS3Client = new AmazonS3Client(lAwsCredentials);
2)Following is the code to calculate md5 2)下面是计算md5的代码
public class MD5CheckSum {
public static byte[] createChecksum(String pFilepath) throws Exception {
InputStream lFis = new FileInputStream(pFilepath);
byte[] lBuffer = new byte[1024];
MessageDigest lMessageDigest = MessageDigest.getInstance("MD5");
int lNumRead;
do {
lNumRead = lFis.read(lBuffer);
if (lNumRead > 0) {
lMessageDigest.update(lBuffer, 0, lNumRead);
}
} while (lNumRead != -1);
lFis.close();
return lMessageDigest.digest();
}
public static String getMD5Checksum(String pFilepath) throws Exception {
byte[] lBytes = createChecksum(pFilepath);
return Base64.encodeToString(lBytes, Base64.DEFAULT);
}
} }
3)Following is the code to set md5 using metadata: 3)以下是使用元数据设置md5的代码:
try {
lMd5 = MD5CheckSum.getMD5Checksum(pFile.getAbsolutePath());
Log.v(TAG, "CheckSum:====" + lMd5);
} catch (Exception lException) {
lException.printStackTrace();
}
ObjectMetadata lObjectMetadata = new ObjectMetadata();
if (lMd5 != null) {
lObjectMetadata.setContentMD5(lMd5);
}`
InitiateMultipartUploadResult mInitResponse = mS3Client.initiateMultipartUpload(new InitiateMultipartUploadRequest(mBucketName, mKeyName,
lObjectMetadata);
But a exception is thrown by amazon when i set md5: 但是当我设置md5时,亚马逊抛出了一个异常:
Caused by: com.amazonaws.services.s3.model.AmazonS3Exception: Anonymous users cannot initiate multipart uploads. 引起原因:com.amazonaws.services.s3.model.AmazonS3Exception:匿名用户无法启动分段上传。 Please authenticate. 请验证。 (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: BA0C68FC884703FD), S3 Extended Request ID: re2sdbzf8MMqGAyrNQOoqYJ8EdXERoWE7cjG+UpfAtFuP5IeAbXmk6Riw+PX8Uw3Jcspn1rSQvI= (服务:Amazon S3;状态代码:403;错误代码:AccessDenied;请求ID:BA0C68FC884703FD),S3扩展请求ID:re2sdbzf8MMqGAyrNQOoqYJ8EdXERoWE7cjG + UpfAtFuP5IeAbXmk6Riw + PX8Uw3J
Is this the correct way to set md5? 这是设置md5的正确方法吗?
Note: When md5 is not set(ie objectmetadata is not set) then upload works without any exception 注意:如果未设置md5(即未设置objectmetadata),则上传将正常进行
I have also faced this type of issue.. 我也遇到过这类问题。
I fixed by adding Base64.DEFAULT
instead of others such as WRAP
and NO_WRAP
. 我通过添加Base64.DEFAULT
而不是诸如WRAP
和NO_WRAP
类的其他Base64.DEFAULT
来进行NO_WRAP
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.