How to Let Others Upload to My S3 Bucket

Intro

Hi guys! Today nosotros are going to talk about uploading files toAmazon S3 Bucket from yourSpring Boot awarding.

As yous may discover virtually each application, mobile or web, gives users an ability to upload their images, photos, avatars etc. So yous, as a developer, should cull the best mode how to save and where to store these files. At that place are dissimilar approaches for storing files:

  • directly on the server where an application is deployed
  • in the database every bit a binary file
  • using some cloud storages

In my programmer practice I always prefer the last arroyo as it seems to be the best one for me (but of course you might accept your own stance). As a cloud service I useS3 Bucket ServiceofAmazonVisitor. And here is why:

  • information technology's easy to programmaticaly upload whatever file using their API
  • Amazon supports a lot of programming languages
  • there is a web interface where yous can see all of your uploaded files
  • you can manually upload/delete any file using web interface

Account Configuration

To showtime usingS3 Bucket you need to create an account on Amazon  website. Registration procedure is easy and clear enough, merely you will have to verify your phone number and enter your credit card info (don't worry, your carte du jour will not be charged if but you purchase some services).

After account cosmos nosotros need to create s3 saucepan. Go toServices -> S3

So press 'Create bucket' button.

Enter your bucket name (should be unique) and choose region that is closest to you lot. Press 'Create' button.

Note: Amazon will requite yous 5GB of storage for costless for the start twelvemonth. After reaching this limit you volition have to pay for using information technology.

Now your saucepan is created merely we demand to give permission for users to access this saucepan. It is not secured to requite the admission keys of your root user to your developer team or someone else. We need to create newIAM userand give him permission to utilize only S3 Bucket.

AWS Identity and Access Direction (IAM) is a web service that helps you lot securely control access to AWS resources.

Let'due south create such user. Go to Services -> IAM . In the navigation pane, chooseUsers and then chooseAdd user.

Enter user's proper name and checkAccess blazon ' Programatic admission '. Press next button. We need to add together permissions to this user. Press ' Attach existing policy directly ', in the search field enter 's3' and amid found permissions choose AmazonS3FullAccess .

Then printing next and 'Create User'. If you did everything correct so you should meet Access cardinal ID  and Secret access key  for your user. There is also 'Download .csv' button for downloading these keys, then please click on information technology in social club non to loose keys.

Our S3 Saucepan configuration is done so allow's continue to Bound Boot application.

Spring Kick Part

Permit'south create Spring Boot projection and add amazon dependency

<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.133</version>
</dependency>

Now let'southward add s3 bucket backdrop to our application.yml  file:

          amazonProperties:
endpointUrl:
https://s3.us-e-2.amazonaws.com
accessKey: XXXXXXXXXXXXXXXXX
secretKey: XXXXXXXXXXXXXXXXXXXXXXXXXX
bucketName: your-bucket-name

It'due south time to create ourRestControllerwith ii request mappings " /uploadFile " and " /deleteFile ".

@RestController
@RequestMapping("/storage/")
public grade BucketController {

individual AmazonClient amazonClient;

@Autowired
BucketController(AmazonClient amazonClient) {
this.amazonClient = amazonClient;
}

@PostMapping("/uploadFile")
public String uploadFile(@RequestPart(value = "file") MultipartFile file) {
return this.amazonClient.uploadFile(file);
}

@DeleteMapping("/deleteFile")
public String deleteFile(@RequestPart(value = "url") Cord fileUrl) {
return this.amazonClient.deleteFileFromS3Bucket(fileUrl);
}
}

At that place is nothing special in the controller, except uploadFile () method recievesMultipartFileas aRequestPart.

This code is actually broken because we don't acceptAmazonClientclass still, so let's create this class with the following fields.

@Service public class AmazonClient {      private AmazonS3 s3client;      @Value("${amazonProperties.endpointUrl}")     private String endpointUrl;       @Value("${amazonProperties.bucketName}")     individual Cord bucketName;    @Value("${amazonProperties.accessKey}")     private Cord accessKey;    @Value("${amazonProperties.secretKey}")     private String secretKey;@PostConstruct     private void initializeAmazon() {        AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);        this.s3client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials))       .withRegion(Regions.US_EAST_2).build(); } }

AmazonS3 is a class from amazon dependency. All other fields are merely a representation of variables from ourawarding.ymlfile. The@Value annotation will demark application properties directly to class fields during application initialization.

Nosotros added method initializeAmazon () to ready amazon credentials to amazon client. Annotation@PostConstruct is needed to run this method after constructor will be called, because form fields marked with@Valueannotation is zilch in the constructor.

S3 bucket uploading method requiresFileequally a parameter, only we haveMultipartFile, so nosotros need to add method which tin make this convertion.

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

Also you can upload the same file many times, so we should generate unique proper name for each of them. Let'due south use a timestamp and likewise replace all spaces in filename with underscores to avoid bug in time to come.

private Cord generateFileName(MultipartFile multiPart) {
return new Engagement().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_");
}

Now permit'south add method which uploads file to S3 bucket.

individual void uploadFileTos3bucket(String fileName, File file) {
s3client.putObject(new PutObjectRequest(bucketName, fileName, file)
.withCannedAcl(CannedAccessControlList.PublicRead));
}

In this method we are adding PublicRead permissions to this file. It means that anyone who accept the file url can access this file. It'southward a good practice for images only, considering you probably will display these images on your website or mobile awarding, so you desire to be sure that each user can see them.

Finally, we will combine all these methods into one general that is called from our controller. This method will save a file to S3 bucket and returnfileUrlwhich you can store to database. For case you tin adhere this url to user'south model if it's a profile image etc.

public String uploadFile(MultipartFile multipartFile) {

String fileUrl = "";
try {
File file = convertMultiPartToFile(multipartFile);
Cord fileName = generateFileName(multipartFile);
fileUrl = endpointUrl + "/" + bucketName + "/" + fileName;
uploadFileTos3bucket(fileName, file);
file.delete();
} catch (Exception due east) {
e.printStackTrace();
}
render fileUrl;
}

The simply affair left to add is deleteFile()  method.

public String deleteFileFromS3Bucket(String fileUrl) {
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
s3client.deleteObject(new DeleteObjectRequest(bucketName + "/", fileName));
return "Successfully deleted";
}

S3 bucket cannot delete file by url. It requires a saucepan name and a file name, that's why nosotros retrieved file name from url.

Testing time

Allow'due south test our awarding past making requests using Postman. We demand to choosePOSTmethod, in theTrunkwe should select ' form-data '. As a key we should enter ' file ' and choose value type 'File'. And then choose any file from your PC as a value. The endpoint url is: http://localhost:8080/storage/uploadFile.

If you did everything right and then y'all should get file url in the response body.

And if you open up your S3 bucket on Amazon then you should see i uploaded image at that place.

Now let's exam our delete method. ChooseDELETE method with endpoint url: http://localhost:8080/storage/deleteFile. Body type is the aforementioned: 'form-data', fundamental: 'url', and into value field enter the fileUrl created by S3 bucket.

Subsequently sending the request you should get the message 'Successfully deleted'.

Decision

That'due south basically it. Now y'all can easily use S3 saucepan in your own projects. Promise this was helpful for you. If y'all have any questions please experience gratuitous to leave a comment. Thank you for reading, as well exercise non forget to printing Clap button if you like this post.

You can cheque out full case of this application on my GitHub business relationship. As well you can bank check it on Oril Software GitHub.

No Article rating

0 Reviews

Was this article helpful? Please charge per unit this commodity to give us valuable insights for our improvements.

mosleyscretwert.blogspot.com

Source: https://oril.co/blog/uploading-files-to-aws-s3-bucket-using-spring-boot-2/

0 Response to "How to Let Others Upload to My S3 Bucket"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel