AmazonS3 putObject with InputStream length example

前端 未结 8 2062
梦如初夏
梦如初夏 2020-12-04 07:36

I am uploading a file to S3 using Java - this is what I got so far:

AmazonS3 s3 = new AmazonS3Client(new BasicAWSCredentials(\"XX\",\"YY\"));

List

        
8条回答
  •  星月不相逢
    2020-12-04 08:00

    For uploading, the S3 SDK has two putObject methods:

    PutObjectRequest(String bucketName, String key, File file)
    

    and

    PutObjectRequest(String bucketName, String key, InputStream input, ObjectMetadata metadata)
    

    The inputstream+ObjectMetadata method needs a minimum metadata of Content Length of your inputstream. If you don't, then it will buffer in-memory to get that information, this could cause OOM. Alternatively, you could do your own in-memory buffering to get the length, but then you need to get a second inputstream.

    Not asked by the OP (limitations of his environment), but for someone else, such as me. I find it easier, and safer (if you have access to temp file), to write the inputstream to a temp file, and put the temp file. No in-memory buffer, and no requirement to create a second inputstream.

    AmazonS3 s3Service = new AmazonS3Client(awsCredentials);
    File scratchFile = File.createTempFile("prefix", "suffix");
    try {
        FileUtils.copyInputStreamToFile(inputStream, scratchFile);    
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, id, scratchFile);
        PutObjectResult putObjectResult = s3Service.putObject(putObjectRequest);
    
    } finally {
        if(scratchFile.exists()) {
            scratchFile.delete();
        }
    }
    

提交回复
热议问题