Upload a File to Server Using Java Spring Boot

Introduction

File upload example using Spring Residue Controller will show you how to upload a file when selected for uploading from whatever client (browser or any client) and Bound Remainder service is used every bit a server side engineering science for uploading the file. The file may be any blazon, i.east., such as excel, text, give-and-take, pdf etc. HereIe will create Jump Boot application equally it reduces the almost of the efforts in project configurations.

Related Posts:

  • Junit Testing of File Upload and Download in Spring REST Controllers
  • File download example using Spring REST Controller

Prerequisites

Coffee at to the lowest degree 8, Gradle 6.1.one – 6.vii.1, Maven 3.six.three, Jump Boot ii.two.5 – 2.iv.3

Projection Setup

Equally a prerequisite I have to first setup the project environment so that I would be able to write the required code for uploading file into server and procedure the file information for our application's demand. Create beneath build.gradle script to add the required projection dependencies. I have also specified the JDK version I will exist using for this application.

          buildscript { 	ext { 		springBootVersion = 'ii.2.5.RELEASE' to 2.four.3 	}     repositories {         mavenCentral()     }     dependencies {         classpath("org.springframework.boot:bound-boot-gradle-plugin:${springBootVersion}")     } }  plugins {     id 'java-library'     id 'org.springframework.boot' version "${springBootVersion}" }  sourceCompatibility = 12 targetCompatibility = 12  repositories {     mavenCentral() }  dependencies {     implementation("org.springframework.boot:spring-boot-starter-web:${springBootVersion}") }        

If you are creating maven based project then you can use below pom.xml file:

          <project 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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 	<modelVersion>4.0.0</modelVersion>  	<groupId>com.roytuts</groupId> 	<artifactId>jump-residual-file-upload</artifactId> 	<version>0.0.i-SNAPSHOT</version>  	<parent> 		<groupId>org.springframework.boot</groupId> 		<artifactId>jump-kicking-starter-parent</artifactId> 		<version>2.2.5.RELEASE to ii.four.3</version> 	</parent>  	<properties> 		<project.build.sourceEncoding>UTF-viii</projection.build.sourceEncoding>                 <maven.compiler.source>12</maven.compiler.source> 		<maven.compiler.target>12</maven.compiler.target> 	</backdrop>  	<dependencies> 		<dependency> 			<groupId>org.springframework.kick</groupId> 			<artifactId>spring-boot-starter-web</artifactId> 		</dependency> 	</dependencies>      <build>         <plugins> 			<plugin> 				<groupId>org.apache.maven.plugins</groupId> 				<artifactId>maven-compiler-plugin</artifactId> 				<version>3.8.1</version> 			</plugin> 		</plugins> 	</build> </project>        

application.properties

I am creating below application.backdrop file under classpath directory src/main/resource to override default file upload size 2MB. Then maximum file size that I can upload is 10MB. Now you can upload a file with maximum size upward to 10MB.

          #multipart max size leap.http.multipart.max-file-size=10MB spring.http.multipart.max-asking-size=10MB        

Bound REST Controller

Create below class that will be used in file upload example using Spring REST Controller to receive the selected file from customer.

I take the beneath method with http method Mail service request and request file parameter file which I will be used for uploading file from client.

I apply the data type as MultipartFile to upload the file (multipart/form-data).

In the controller method I check whether file has been uploaded or non and if uploaded then I excerpt the file information and log using Coffee's born logger API.

Finally I send the file name equally the response to the customer. In real application, ideally you lot would process the file data in Service layer code afterwards receiving the file in Spring Residual Controller but here I accept just shown the idea how to upload a file using Spring Balance service.

          package com.roytuts.controller;  import java.io.InputStream; import java.util.logging.Logger;  import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.demark.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile;  @RestController public grade FileUploadRestController {  	private static final Logger logger = Logger.getLogger(FileUploadRestController.form.getName());  	@PostMapping("/upload") 	public ResponseEntity<Cord> uploadData(@RequestParam("file") MultipartFile file) throws Exception {  		if (file == cypher) { 			throw new RuntimeException("You must select the a file for uploading"); 		}  		InputStream inputStream = file.getInputStream(); 		String originalName = file.getOriginalFilename(); 		Cord proper noun = file.getName(); 		String contentType = file.getContentType(); 		long size = file.getSize();  		logger.info("inputStream: " + inputStream); 		logger.info("originalName: " + originalName); 		logger.info("name: " + name); 		logger.info("contentType: " + contentType); 		logger.info("size: " + size);  		// Do processing with uploaded file data in Service layer 		return new ResponseEntity<Cord>(originalName, HttpStatus.OK); 	}  }        

Spring Boot Main Class

Create beneath Spring Boot main form in order to see the file upload instance using Leap REST Controller in action. This main class deploys the awarding in embedded Tomcat server and runs on port 8080.

You demand to scan the base packages then that each annotated form (@Controller, @RESTController, @Repository, @Service, @Component etc.) volition be picked upwards from that package or child packages.

          package com.roytuts.main;  import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;  @SpringBootApplication(scanBasePackages = "com.roytuts") public grade Application {  	public static void main(String[] args) { 		SpringApplication.run(Application.grade, args); 	}  }        

Testing the Awarding

Now it's time to test our file upload example application. You can examination this awarding using Balance client, i.eastward., using Postman and you don't need whatsoever fancy UI for that.

Now open Postman Residual client and upload any file and check the output in the console logger.

You need to do the following steps:

  1. Choose http method as POST
  2. Choose class-information in the torso option
  3. Put the value for key as file
  4. Choose File instead of Text
  5. Browse and select file
  6. Click on Transport.
file upload example using spring rest controller

Console Output

The console output volition display about the file information:

          936  INFO 18504 --- [nio-8080-exec-ii] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Jump DispatcherServlet 'dispatcherServlet' 937  INFO 18504 --- [nio-8080-exec-two] o.s.spider web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet' 939  INFO 18504 --- [nio-8080-exec-ii] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms 113  INFO 18504 --- [nio-8080-exec-2] c.r.controller.FileUploadRestController  : inputStream: coffee.io.FileInputStream@1bf3ba5e 113  INFO 18504 --- [nio-8080-exec-2] c.r.controller.FileUploadRestController  : originalName: employee.sql 113  INFO 18504 --- [nio-8080-exec-2] c.r.controller.FileUploadRestController  : name: file 113  INFO 18504 --- [nio-8080-exec-ii] c.r.controller.FileUploadRestController  : contentType: application/x-sql 114  INFO 18504 --- [nio-8080-exec-two] c.r.controller.FileUploadRestController  : size: 2750        

That'southward all. Hope yous got idea on file upload example using Jump REST Controller.

Source Code

Download

wisecoustopeceir.blogspot.com

Source: https://roytuts.com/file-upload-example-using-spring-rest-controller/

0 Response to "Upload a File to Server Using Java Spring Boot"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel