AmazonS3 putObject with InputStream length example

前端 未结 8 2070
梦如初夏
梦如初夏 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 07:42

    If all you are trying to do is solve the content length error from amazon then you could just read the bytes from the input stream to a Long and add that to the metadata.

    /*
     * Obtain the Content length of the Input stream for S3 header
     */
    try {
        InputStream is = event.getFile().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 metadata = new ObjectMetadata();
    metadata.setContentLength(contentLength);
    
    /*
     * Reobtain the tmp uploaded file as input stream
     */
    InputStream inputStream = event.getFile().getInputstream();
    
    /*
     * Put the object in S3
     */
    try {
    
        s3client.putObject(new PutObjectRequest(bucketName, keyName, inputStream, metadata));
    
    } catch (AmazonServiceException ase) {
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Error Message: " + ace.getMessage());
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
    

    You'll need to read the input stream twice using this exact method so if you are uploading a very large file you might need to look at reading it once into an array and then reading it from there.

提交回复
热议问题