简体   繁体   English

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

[英]AmazonS3, how to check if the upload succeeded?

I wrote a short test code in Java to upload a PDF file generated in memory. 我用Java编写了一个简短的测试代码来上传在内存中生成的PDF文件。 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. 在这个测试代码中我只使用一个虚拟字节数组,但在实际使用中,我将在该字节数组中放置一个生成的PDF(最多2-3页)。 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. 然而,因为我已经返回PutObjectResult,我想知道我应该如何检查它。 Or is it enough to look for the exceptions AmazonClientException and AmazonServiceException? 或者是否足以查找AmazonClientException和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: 我查看了AWS的源代码并对其进行了调试并发现了以下内容:

  • If MD5 is not provided it's calculated (works either for real files and InputStream) 如果没有提供MD5,则计算它(适用于真实文件和InputStream)
  • When the upload is finished md5 client side and server side are compared and if they differ an AmazonClientException is thrown. 上传完成后,将比较md5客户端和服务器端,如果它们不同,则抛出AmazonClientException。 [line 1188 of AmazonS3Client 1.19] [AmazonS3Client 1.19第1188行]

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. 换句话说,为了回答我自己的问题,它就足以监听异常,因为还检查了上传数据的MD5,因此如果存在损坏,则会引发异常。

AmazonClientException and AmazonServiceException are unchecked exceptions, so it's important to remember to listen for them since the compiler won't force you to. AmazonClientException和AmazonServiceException是未经检查的异常,因此记住监听它们非常重要,因为编译器不会强制您这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM