AmazonS3,如何检查是否上传成功了吗?上传

2023-09-12 23:36:19 作者:ㄗs:泪痕

我写了一个简短的测试code在Java中上传在内存中生成一个PDF文件。在本次测试code我只是用一个虚拟的字节数组,但在实际使用中笔者将会把生成的PDF(最多2-3页)在该字节数组。一切正常:该文件被上传和权限设置

不过,因为我有一个PutObjectResult回来了,我想知道如何我应该检查一下。或者是不够看的例外AmazonClientException和AmazonServiceException?

在换句话说:如何检查上传succeded并没有破坏我的数据

 字符串桶=mybucket.example.com;
    字符串文件名=2011 /测试/的test.pdf;
    AmazonS3客户端=新AmazonS3Client(新BasicAWSCredentials(
        ACCESSKEY,SecretKey的));
    字节[]内容=新的字节[] {1,2,3,4,5,6,7,8,9,10,11};
    InputStream的流=新ByteArrayInputStream的(内容);
    ObjectMetadata元=新ObjectMetadata();
    meta.setContentLength(contents.length);
    meta.setContentType(应用程序/ PDF格式);
    PutObjectResult解析度= client.putObject(桶,文件名,流元);
    client.setObjectAcl(桶,文件名,CannedAccessControlList.PublicRead);
 

解决方案

我看AWS的来源$ C ​​$ c和调试,并发现了以下内容:

如果未提供的MD5它的计算(作品无论是真实的文件和InputStream的) 在当前MD5客户端和服务器端进行比较,如果它们不同的AmazonClientException被抛出上传完毕。 [行AmazonS3Client 1.19 1188] 详解Amazon S3上传 下载数据

在换句话说,要回答我的问题,这是不够的例外听,因为还上传了数据的MD5检查,因此,如果有一个腐败的异常将得到提升。

AmazonClientException和AmazonServiceException是强制异常,所以记得要听他们的,因为编译器不会强迫你这是非常重要的。

I wrote a short test code in Java to upload a PDF file generated in memory. In this test code I just use a dummy byte array, but in the real use I will put a generated PDF (max 2-3 pages) in that byte array. Everything works: the file gets uploaded and the permissions set.

However since I've a PutObjectResult returned, I was wondering how I'm supposed to check it. Or is it enough to look for the exceptions AmazonClientException and AmazonServiceException?

In other words: How to check that the upload succeded and didn't corrupt my data?

    String bucket = "mybucket.example.com";
    String fileName = "2011/test/test.pdf";
    AmazonS3 client = new AmazonS3Client(new BasicAWSCredentials(
        "accessKey", "secretKey"));
    byte[] contents = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
    InputStream stream = new ByteArrayInputStream(contents);
    ObjectMetadata meta = new ObjectMetadata();
    meta.setContentLength(contents.length);
    meta.setContentType("application/pdf");
    PutObjectResult res = client.putObject(bucket, fileName, stream, meta);
    client.setObjectAcl(bucket, fileName, CannedAccessControlList.PublicRead);

解决方案

I've looked the source code of AWS and debugged it and discovered the following:

If MD5 is not provided it's calculated (works either for real files and InputStream) When the upload is finished md5 client side and server side are compared and if they differ an AmazonClientException is thrown. [line 1188 of AmazonS3Client 1.19]

In other words, to answer my own question, it's enough to listen for the exceptions because also the MD5 of the data uploaded is checked, so if there was a corruption an exception would be raised.

AmazonClientException and AmazonServiceException are unchecked exceptions, so it's important to remember to listen for them since the compiler won't force you to.

 
精彩推荐
图片推荐