Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload multipart file to AWS without saving it locally

I wrote a Rest API that accepts MultipartFile. I want to upload the files that come in to Amazon S3. The problem is that I don't know a way other than first saving it to the local system before uploading it to S3. Is there any way to do so?

Right now, there is an issue in saving the file locally and I'm looking for a work around: Multipart transferTo looks for a wrong file address when using createTempFile

like image 280
Arian Avatar asked May 09 '18 08:05

Arian


1 Answers

Yes, you can do this.Use putObject which consume InputStream as param. Here is sample code.

public void saveFile(MultipartFile multipartFile) throws AmazonServiceException, SdkClientException, IOException {
    ObjectMetadata data = new ObjectMetadata();
    data.setContentType(multipartFile.getContentType());
    data.setContentLength(multipartFile.getSize());
    BasicAWSCredentials creds = new BasicAWSCredentials("accessKey", "secretKey");
    AmazonS3 s3client = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_2).withCredentials(new AWSStaticCredentialsProvider(creds)).build();
    PutObjectResult objectResult = s3client.putObject("myBucket", multipartFile.getOriginalFilename(), multipartFile.getInputStream(), data);
    System.out.println(objectResult.getContentMd5()); //you can verify MD5
}

You can find javadoc here

like image 161
Nitin Avatar answered Oct 23 '22 14:10

Nitin