im new in s3 and i need some help please/
1.I get some file from rest api its looks like
@PostMapping ("/aaa")
public void aaa(@RequestParam("file")MultipartFile file)
how do i can put it to s3 without saving in local like this
File f=new File(System.getProperty("java.io.tmpdir")+"/"+file.getOriginalFilename());
file.transferTo(f);
s3client.putObject("netapi", file.getOriginalFilename(),f);
i need to put file like it is - for example i put img.png to rest api and i need to get link from s3 to same file that be able to download and open without any converting on client pc
2.second question is there any way to do not use MultipartFile in rest api - may be there is a way to covert inputStream that i can get from HttpServletRequest.getInputStream() to a file with same file name and file extension
i use sdk for java 1.X
implementation(group = "com.amazonaws",name="aws-java-sdk-s3",version = "1.11.1008")
To answer your question about working with a Spring Controller, you can get the byte array that represents the file like this:
//Upload an image to send to a S3 bucket
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public ModelAndView singleFileUpload(@RequestParam("file") MultipartFile file) {
try {
// Now i can add this to an S3 Bucket
byte[] bytes = file.getBytes();
String name = file.getOriginalFilename() ;
// Put the file into the bucket
s3Client.putObject(bytes, "mybucket", name);
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView(new RedirectView("photo"));
}
YOu can use that byte array and file name to put the file into an Amazon S3 bucket without saving it as a local file.
To put this into an AMazon S3 bucket, you can use this code:
// Places the file into a S3 bucket
public String putObject(byte[] data, String bucketName, String objectKey) {
s3 = getClient();
try {
//Put a file into the bucket
PutObjectResponse response = s3.putObject(PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build(),
RequestBody.fromBytes(data));
return response.eTag();
} catch (S3Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
return "";
}
private S3Client getClient() {
// Create the S3Client object
Region region = Region.US_WEST_2;
S3Client s3 = S3Client.builder()
.credentialsProvider(EnvironmentVariableCredentialsProvider.create())
.region(region)
.build();
return s3;
}
This code shows you how to handle a file that is posted to a Spring BOOT controller, how to get the file name and byte array, and how to put the file into an Amazon S3 bucket using V2 S3 code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With