sping boot multipart file upload java client
In this tutorial, I will show you how to upload multiple files and download with a Leap Boot Rest APIs. We also use Spring Spider web MultipartFile
interface to handle HTTP multi-part requests and Postman to bank check the result.
Related Posts:
– Athwart 8 + Jump Boot: File upload instance
– React + Spring Kicking: File upload example
Deployment: Deploy Spring Boot App on AWS – Elastic Beanstalk
Jump Boot Rest APIs for uploading multiple Files
Our Leap Boot Application will provide APIs for:
- uploading multiple Files to Server
- downloading File from server with the link
- getting listing of Files' information (file name & url)
These are APIs to be exported:
Methods | Urls | Actions |
---|---|---|
/upload | upload multiple Files | |
Go | /files | get List of Files (name & url) |
Become | /files/[filename] | download a File |
Engineering
- Coffee viii
- Spring Boot two (with Spring Web MVC)
- Maven 3.6.i
Project Structure
Let me explain it briefly.
– FileInfo
contains information of the uploaded file.
– FilesStorageService
helps u.s. to initialize storage, save new file, load file, get listing of Files' info, delete all files.
– FilesController
uses FilesStorageService
to consign Balance APIs: POST multiple files, GET all files' information, download a File.
– FileUploadExceptionAdvice
handles exception when the controller processes file upload.
– application.properties contains configuration for Servlet Multipart.
– pom.xml for Spring Boot dependency.
Setup Bound Boot Multiple Files upload project
Use Leap web tool or your development tool (Jump Tool Suite, Eclipse, Intellij) to create a Jump Boot project.
Then open pom.xml and add these dependencies:
<dependency> <groupId>org.springframework.kick</groupId> <artifactId>spring-kicking-starter-web</artifactId> </dependency>
Create Service for File Storage
First we demand an interface that will be autowired in the Controller.
In service binder, create FilesStorageService
interface like following code:
service/FilesStorageService.java
package com.bezkoder.spring.files.uploadmultiple.service; import coffee.nio.file.Path; import coffee.util.stream.Stream; import org.springframework.cadre.io.Resources; import org.springframework.web.multipart.MultipartFile; public interface FilesStorageService { public void init(); public void save(MultipartFile file); public Resource load(String filename); public void deleteAll(); public Stream<Path> loadAll(); }
Now nosotros create implementation of the interface.
service/FilesStorageServiceImpl.java
parcel com.bezkoder.leap.files.uploadmultiple.service; import java.io.IOException; import coffee.internet.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.stereotype.Service; import org.springframework.util.FileSystemUtils; import org.springframework.spider web.multipart.MultipartFile; @Service public class FilesStorageServiceImpl implements FilesStorageService { individual final Path root = Paths.get("uploads"); @Override public void init() { try { Files.createDirectory(root); } grab (IOException e) { throw new RuntimeException("Could not initialize folder for upload!"); } } @Override public void save(MultipartFile file) { try { Files.copy(file.getInputStream(), this.root.resolve(file.getOriginalFilename())); } take hold of (Exception e) { throw new RuntimeException("Could not store the file. Error: " + e.getMessage()); } } @Override public Resource load(String filename) { endeavor { Path file = root.resolve(filename); Resource resource = new UrlResource(file.toUri()); if (resource.exists() || resource.isReadable()) { return resource; } else { throw new RuntimeException("Could non read the file!"); } } take hold of (MalformedURLException e) { throw new RuntimeException("Fault: " + e.getMessage()); } } @Override public void deleteAll() { FileSystemUtils.deleteRecursively(root.toFile()); } @Override public Stream<Path> loadAll() { try { render Files.walk(this.root, i).filter(path -> !path.equals(this.root)).map(this.root::relativize); } take hold of (IOException e) { throw new RuntimeException("Could not load the files!"); } } }
Define Data Models
In model package, let's create FileInfo
which has fields: proper name
& url
.
model/FileInfo.java
package com.bezkoder.jump.files.uploadmultiple.model; public grade FileInfo { private String name; private String url; public FileInfo(Cord name, String url) { this.name = name; this.url = url; } public String getName() { render this.name; } public void setName(String proper noun) { this.proper noun = name; } public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } }
Define Response Message
ResponseMessage
will be used for sending message to customer in Controller and Exception Handler.
message/ResponseMessage.java
bundle com.bezkoder.bound.files.uploadmultiple.bulletin; public class ResponseMessage { private String message; public ResponseMessage(Cord message) { this.message = message; } public String getMessage() { return bulletin; } public void setMessage(String message) { this.bulletin = message; } }
Create Controller for upload multiple Files & download
In controller package, we create FilesController
.
controller/FilesController.java
package com.bezkoder.spring.files.uploadmultiple.controller; import coffee.util.ArrayList; import java.util.Arrays; import coffee.util.List; import java.util.stream.Collectors; import org.springframework.beans.manufacturing plant.notation.Autowired; import org.springframework.cadre.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.spider web.bind.annotation.CrossOrigin; import org.springframework.web.demark.annotation.GetMapping; import org.springframework.web.bind.notation.PathVariable; import org.springframework.spider web.demark.annotation.PostMapping; import org.springframework.spider web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.spider web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; import com.bezkoder.spring.files.uploadmultiple.model.FileInfo; import com.bezkoder.spring.files.uploadmultiple.model.ResponseMessage; import com.bezkoder.spring.files.uploadmultiple.service.FilesStorageService; @Controller @CrossOrigin("http://localhost:8081") public course FilesController { @Autowired FilesStorageService storageService; @PostMapping("/upload") public ResponseEntity<ResponseMessage> uploadFiles(@RequestParam("files") MultipartFile[] files) { Cord message = ""; attempt { List<String> fileNames = new ArrayList<>(); Arrays.asList(files).stream().forEach(file -> { storageService.save(file); fileNames.add together(file.getOriginalFilename()); }); bulletin = "Uploaded the files successfully: " + fileNames; return ResponseEntity.status(HttpStatus.OK).trunk(new ResponseMessage(message)); } catch (Exception due east) { message = "Neglect to upload files!"; return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).torso(new ResponseMessage(message)); } } @GetMapping("/files") public ResponseEntity<List<FileInfo>> getListFiles() { List<FileInfo> fileInfos = storageService.loadAll().map(path -> { String filename = path.getFileName().toString(); Cord url = MvcUriComponentsBuilder .fromMethodName(FilesController.class, "getFile", path.getFileName().toString()).build().toString(); render new FileInfo(filename, url); }).collect(Collectors.toList()); render ResponseEntity.status(HttpStatus.OK).trunk(fileInfos); } @GetMapping("/files/{filename:.+}") public ResponseEntity<Resource> getFile(@PathVariable String filename) { Resource file = storageService.load(filename); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } }
– @CrossOrigin
is for configuring allowed origins.
– @Controller
annotation is used to define a controller.
– @GetMapping
and @PostMapping
annotation is for mapping HTTP GET & Postal service requests onto specific handler methods:
- Postal service /upload:
uploadFiles()
- Get /files:
getListFiles()
- GET /files/[filename]:
getFile()
– We use @Autowired
to inject implementation of FilesStorageService
edible bean to local variable.
The main method is uploadFiles()
in which nosotros utilize MultipartFile[] files
as an argument, and Java 8 Stream API to work with each file in the assortment.
Configure Multipart File for Servlet
Let's ascertain the maximum file size that can be uploaded in application.backdrop as following:
spring.servlet.multipart.max-file-size=500KB leap.servlet.multipart.max-request-size=500KB
– spring.servlet.multipart.max-file-size
: max file size for each request.
– spring.servlet.multipart.max-asking-size
: max request size for a multipart/form-data.
Handle File Upload Exception
This is where we handle the case in that a asking exceeds Max Upload Size. The arrangement will throw MaxUploadSizeExceededException
and we're gonna apply @ControllerAdvice
with @ExceptionHandler
annotation for handling the exceptions.
exception/FileUploadExceptionAdvice.java
package com.bezkoder.spring.files.uploadmultiple.exception; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.bezkoder.bound.files.uploadmultiple.model.ResponseMessage; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.demark.annotation.ControllerAdvice; import org.springframework.spider web.bind.annotation.ExceptionHandler; @ControllerAdvice public class FileUploadExceptionAdvice extends ResponseEntityExceptionHandler { @ExceptionHandler(MaxUploadSizeExceededException.grade) public ResponseEntity<ResponseMessage> handleMaxSizeException(MaxUploadSizeExceededException exc) { return ResponseEntity .status(HttpStatus.EXPECTATION_FAILED) .trunk(new ResponseMessage("One or more files are too big!")); } }
Initialize Storage
We need to run init()
method of FilesStorageService
(and also deleteAll()
if necessary). So open up SpringBootUploadMultipleFilesApplication.java and implement CommandLineRunner
for run()
method like this:
package com.bezkoder.spring.files.uploadmultiple; import javax.annotation.Resource; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.kick.autoconfigure.SpringBootApplication; import com.bezkoder.spring.files.uploadmultiple.service.FilesStorageService; @SpringBootApplication public form SpringBootUploadMultipleFilesApplication implements CommandLineRunner { @Resource FilesStorageService storageService; public static void primary(String[] args) { SpringApplication.run(SpringBootUploadMultipleFilesApplication.class, args); } @Override public void run(String... arg) throws Exception { storageService.deleteAll(); storageService.init(); } }
Jump Boot upload Multiple Files with Postman
Run Jump Boot awarding with command: mvn spring-boot:run
.
Refresh the project directory and you will meet uploads folder inside information technology.
Let'south utilize Postman to make some requests.
– Upload some files: In the Torso tab, chose course-data, central files as File type. For value column, choose several files from your PC.
– Upload files which contains certain file with size larger than max file size (500KB):
– Check uploads folder:
– Call back list of Files' information:
– Now you can download whatsoever file from one of the paths higher up.
For example: http://localhost:8080/files/bezkoder.doc
.
Conclusion
Today nosotros've learned how to create Java Spring Kick Application to upload multiple files and go files' data via Residual API.
You can detect the consummate source code for this tutorial on Github.
This mail service explains how to build Angular Client to work with Spring Boot Server.
Happy Learning! See you once more.
Further Reading
- Multipart Content-Type
Source: https://www.bezkoder.com/spring-boot-upload-multiple-files/
0 Response to "sping boot multipart file upload java client"
Post a Comment