AYUSH SHRESTHA
AYUSH SHRESTHA

Reputation: 11

Upload multi part file to S3

I am using spring boot and I have a multipart file from request that I need to upload to S3,but S3 only supports file(not multipart file) to upload to S3. How to upload multipart file to s3

Upvotes: 0

Views: 3705

Answers (2)

DEBENDRA DHINDA
DEBENDRA DHINDA

Reputation: 1193

You can do as follows :

public class S3Utility{
    public static String upload(String bucket, String fileName, InputStream inputStream, String contentType, AmazonS3 s3Client, boolean isPublic) {
    if (inputStream != null) {
      try {
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(inputStream.available());
        meta.setContentType(contentType);

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, inputStream, meta);

        if (isPublic) {
          putObjectRequest = putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead);
        }

        PutObjectResult result = S3Util.getAmazonS3Client(s3Client).putObject(putObjectRequest);
        if (result != null) {
          return fileName;
        }

      } catch (Exception e) {
        log.error("Error uploading file on S3: ", e);
      }
    } else {
      log.warn("Content InputStream is null. Not Uploading on S3");
    }
    return null;
  }
}


@RestController
 public class TestController{


   @PostMapping(path = "upload/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> uploadStampPageImage( @RequestPart(value = "file") MultipartFile imageFile) {

        if(Objets.nonNull(file)){
          String uploadedFilePath = S3Utility.upload("myBucket","myFile.jpg",file.getInputStream(),file.getContentType(), amazonS3Client, true);
          return new ResponseEntity.ok(uploadedFilePath);
        }
        return new ResponseEntity.failure("Not uploaded");

    }

}

 }

Upvotes: 3

Yudeep Rajbhandari
Yudeep Rajbhandari

Reputation: 311

You can convert the multipart file to file like this:

private File convertMultiPartToFile(MultipartFile file) throws IOException {
    File convFile = new File(file.getOriginalFilename());
    FileOutputStream fos = new FileOutputStream(convFile);
    fos.write(file.getBytes());
    fos.close();
    return convFile;
}

But this will create a file in your system s you need to delete it after you upload it using :

if(file.exists()){
  FileUtils.deleteQuietly(file);
}

But if you don't want to involve this path then you can directly upload the stream to s3.

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

where:

input =file.getinputstream();
ObjectMetadata metadata=new ObjectMetadata();
metadata.setContentLength(file.size());

Upvotes: 0

Related Questions