How to Upload a String to a File on S3 Javas


Hey guys in this mail service, nosotros will talk over uploading file to AWS S3 saucepan in Spring boot awarding with full coding example.

Watch the Video


Consummate Example


We volition create this case step past step, follow this tutorial till the terminate

Read More:

  • Check the Complete AWS Tutorial
  • Check the Consummate Leap Boot and Thymeleaf Tutorial
  • Check the Complete JavaServer Faces (JSF) Tutorial
  • Bank check the Complete Spring Data JPA Tutorial
  • Check the Complete Spring Security Tutorial
  • Cheque the Javascript Projects for Beginners
  • Check the Leap Boot JdbcTemplate Tutorials

Create a S3 Bucket on AWS


one. Login in to your AWS business relationship, and go to services, click on the S3 service

Screenshot-2021-08-13-at-3-05-57-PM

ii. On the S3 service, click on the Create Bucket option to create new bucket

Screenshot-2021-08-13-at-3-06-36-PM

3. Side by side enter the Bucket name (requite unique name for the bucket), and make certain to Uncheck Block all public access

Screenshot-2021-08-13-at-3-16-00-PM

Screenshot-2021-08-13-at-3-16-33-PM

iv. Create Access central and Secret central, go to your profile and select My Security Credentials

Screenshot-2021-08-13-at-3-31-36-PM

Create spring kicking project


At that place are many dissimilar ways to create a bound kicking awarding, you lot can follow the beneath articles to create one –

>> Create spring kick application using Spring initializer
>> Create spring boot awarding in Jump tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open up pom.xml and add the following dependencies –

            <?xml version="1.0" encoding="UTF-8"?> <projection xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://world wide web.w3.org/2001/XMLSchema-instance" 	xsi:schemaLocation="http://maven.apache.org/POM/four.0.0 https://maven.apache.org/xsd/maven-four.0.0.xsd"> 	<modelVersion>4.0.0</modelVersion> 	<parent> 		<groupId>org.springframework.boot</groupId> 		<artifactId>bound-kicking-starter-parent</artifactId> 		<version>ii.5.3</version> 		<relativePath/> <!-- lookup parent from repository --> 	</parent> 	<groupId>in.bushansirgur</groupId> 	<artifactId>springboot-file-upload-aws-s3</artifactId> 	<version>ane.0.0</version> 	<name>springboot-file-upload-aws-s3</proper name> 	<clarification>Spring Kick AWS S3 File Upload</clarification> 	<backdrop> 		<coffee.version>xvi</java.version> 	</properties> 	<dependencies> 	 		<dependency> 			<groupId>org.springframework.boot</groupId> 			<artifactId>spring-kick-starter-web</artifactId> 		</dependency>  		<dependency> 			<groupId>org.springframework.kicking</groupId> 			<artifactId>spring-kick-devtools</artifactId> 			<telescopic>runtime</scope> 			<optional>true</optional> 		</dependency> 		 		<dependency> 			<groupId>org.springframework.boot</groupId> 			<artifactId>spring-kicking-starter-test</artifactId> 			<scope>exam</telescopic> 		</dependency> 		 		<dependency> 			<groupId>io.awspring.cloud</groupId> 			<artifactId>spring-cloud-aws-context</artifactId> 			<version>2.3.1</version> 		</dependency>  		<dependency> 			<groupId>io.awspring.cloud</groupId> 			<artifactId>bound-cloud-aws-autoconfigure</artifactId> 			<version>2.three.ane</version> 		</dependency> 	 	</dependencies>  	<build> 		<plugins> 			<plugin> 				<groupId>org.springframework.kick</groupId> 				<artifactId>spring-kick-maven-plugin</artifactId> 			</plugin> 		</plugins> 	</build>  </project>                      

spring-kicking-starter-web dependency for building spider web applications using Spring MVC. Information technology uses the tomcat as the default embedded container. bound-boot-devtools dependency for automatic reloads or alive reload of applications.


leap-deject-aws-context and spring-cloud-aws-autoconfigure dependencies for accessing aws services from spring boot application.

Configure AWS S3 Credentials


Open application.properties file and add together the post-obit contents

            cloud.aws.credentials.admission-primal=YOUR_ACCESS_KEY cloud.aws.credentials.secret-key=YOUR_SECRET_KEY cloud.aws.region.static=us-due east-1 cloud.aws.stack.auto=false  spring.servlet.multipart.max-file-size=100MB leap.servlet.multipart.max-request-size=100MB                      

Brand sure to enter your access key and undercover central

Create a service


Create FileService.coffee interface inside src/main/java and add the following contents

            packet in.bushansirgur.springbootfileupload.service;  import org.springframework.web.multipart.MultipartFile;  public interface FileService {  	String uploadFile(MultipartFile file); }                      

Create AWSS3Service.java form inside src/main/java and the following contents. This class implements FileService so we need to override 1 of the method uploadFile() and provide the implementation for that

            parcel in.bushansirgur.springbootfileupload.service;  import java.io.IOException; import java.util.UUID;  import org.springframework.beans.mill.note.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.spider web.multipart.MultipartFile; import org.springframework.web.server.ResponseStatusException;  import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.ObjectMetadata;  @Service public form AWSS3Service implements FileService{ 	@Autowired 	private AmazonS3Client awsS3Client; 	 	@Override 	public String uploadFile(MultipartFile file) { 		 		String filenameExtension = StringUtils.getFilenameExtension(file.getOriginalFilename()); 		 		String key = UUID.randomUUID().toString() + "." +filenameExtension; 		 		ObjectMetadata metaData = new ObjectMetadata(); 		metaData.setContentLength(file.getSize()); 		metaData.setContentType(file.getContentType()); 		 		try { 			awsS3Client.putObject("my-videos-bucket-05", key, file.getInputStream(), metaData); 		} take hold of (IOException east) { 			throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "An exception occured while uploading the file"); 		} 		 		awsS3Client.setObjectAcl("my-videos-bucket-05", key, CannedAccessControlList.PublicRead); 		 		return awsS3Client.getResourceUrl("my-videos-bucket-05", key); 	} }                      

We will call S3 saucepan put() method to store the file, awsS3Client.put() takes iv parameters,

  • bucketName The name of an existing bucket, to which you accept Permission.Write permission.
  • key The central under which to store the specified file.
  • input The input stream containing the data to be uploaded to Amazon S3.
  • metadata Boosted metadata instructing Amazon S3 how to handle the uploaded information (eastward.chiliad. custom user metadata, hooks for specifying content blazon, etc.).

Side by side we will set the access control list to public using setObjectAcl() , it takes 3 parameters

  • bucketName The name of the bucket containing the object whose ACL is being set.
  • primal The fundamental of the object inside the specified saucepan whose ACL is being set.
  • acl The new pre-configured CannedAccessControlList for the specified object.

Next we will call getResourceUrl() to get the public URL of the specific file, it takes two parameters

  • bucketName
  • key

Create a Rest controller


Create UploadFileController.java class within src/main/java and add together the following contents

            bundle in.bushansirgur.springbootfileupload.controller;  import java.util.HashMap; import java.util.Map;   import org.springframework.beans.factory.notation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.demark.notation.RequestMapping; import org.springframework.web.bind.notation.RequestParam; import org.springframework.web.demark.annotation.RestController; import org.springframework.web.multipart.MultipartFile;  import in.bushansirgur.springbootfileupload.service.AWSS3Service;  @RestController @RequestMapping("/api/file") public course UploadFileController { 	 	@Autowired 	individual AWSS3Service awsS3Service; 	 	@PostMapping 	public ResponseEntity<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) { 		String publicURL = awsS3Service.uploadFile(file); 		Map<String, String> response = new HashMap<>(); 		response.put("publicURL", publicURL); 		return new ResponseEntity<Map<String, Cord>>(response, HttpStatus.CREATED); 	} }                      

Run the app


Run the application using the below maven command –

            mvn spring-kick:run          

Open the Postman and enter the post-obit URL –

  • localhost:8080/api/file

Screenshot-2021-08-13-at-4-03-26-PM

Screenshot-2021-08-13-at-4-03-53-PM

That's it for this post, if you like this post, share this with your friends and colleagues or you can share this inside your social media platform. Thanks, I will see you in our next post.


polingfromete.blogspot.com

Source: https://bushansirgur.in/spring-boot-upload-file-to-aws-s3/

0 Response to "How to Upload a String to a File on S3 Javas"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel