为什么amazon-aws-jdk 1.11.95在将图像上传到AWS S3时会返回File not found异常?

时间:2017-10-10 16:57:51

标签: amazon-web-services amazon-s3 aws-sdk

我正在尝试将图像上传到AWS S3。

Web应用程序在tomcat服务器的本地桌面上运行。 当我从服务器上传图像时,我在http请求多部分文件中看到了文件详细信息,我可以获得它的大小和细节。

这是我设置连接的方式

 File convFile = new File( file.getOriginalFilename());
            file.transferTo(convFile);  

 AmazonS3 s3 =   AmazonS3ClientBuilder.standard()
                .withRegion(Regions.US_WEST_2) //regionName is a string for a region not supported by the SDK yet
                .withCredentials(new AWSStaticCredentialsProvider
                    (new BasicAWSCredentials("key", "accessId")))
//                .setEndpointConfiguration(new EndpointConfiguration("https://s3.console.aws.amazon.com", "us-west-1"))

                .enablePathStyleAccess()
                .disableChunkedEncoding()                
                 .build();  
 s3.putObject(new PutObjectRequest(bucketName, "key", convFile));

我尝试了两种方法。

1)将Multipart文件转换为java.io.File并上传

Error: com.amazonaws.SdkClientException: Unable to calculate MD5 hash: MyImage.png (No such file or directory)

2)将图像作为字节流发送

Error: I am getting java.io.FileNotFound Exception: /path/to/tomcat/MyImage.tmp not found

实际图片名称为MyImage.png。

无论我尝试哪种方法,我都会遇到异常。

1 个答案:

答案 0 :(得分:0)

确定。有几个问题。

  1. 我错误地为不同的键组键入了Region。
  2. 但问题仍然存在,我又回到了1.11.76版本。还有一些问题,这就是我修复的方法。

                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentType(file.getContentType());
                byte[] contentBytes = null;
                try {
                  InputStream is = file.getInputStream();
                  contentBytes = IOUtils.toByteArray(is);
                } catch (IOException e) {
                  System.err.printf("Failed while reading bytes from %s", e.getMessage());
                } 
    
              Long contentLength = Long.valueOf(contentBytes.length);
              objectMetadata.setContentLength(contentLength);
              objectMetadata.setHeader("filename", fileNameWithExtn);
    
              /*
               * Reobtain the tmp uploaded file as input stream
               */
              InputStream inputStream = file.getInputStream();
    
              File convFile = new File(fileNameWithExtn); //If i don't do //this, I think I was getting file not found or MD5 error.
              file.transferTo(convFile); 
    
              FileUtils.copyInputStreamToFile(inputStream, convFile);  //you //need to have commons.io in your pom.xml for this FileUtils to work. Not //the apache FileUtils. 
        AmazonS3 s3 = new AmazonS3Client(new AWSStaticCredentialsProvider
                        (new BasicAWSCredentials("<yourkeyId>", "<YourAccessKey>")));        
                s3.setRegion(Region.US_West.toAWSRegion());   
                s3.setEndpoint("yourRegion.amazonaws.com"); 
                versionId = s3.putObject(new PutObjectRequest("YourBucketName", name, convFile)).getVersionId();