Uploading a File via Rest Call Using Spring Resttemplate
In this tutorial, I will testify you lot how to upload and download files with a Bound Kick Rest APIs to/from a static folder. We also use Leap Web MultipartFile interface to handle HTTP multi-function requests.
This Jump Boot App works with:
– Athwart viii Customer / Angular 10 Customer / Athwart 11 Client / Athwart 12
– Angular Textile 12
– Vue Client / Vuetify Client
– React Client / React Hooks Client
– Material UI Customer
– React Image Upload with Preview
– Axios Client
Related Posts:
– How to upload multiple files in Java Spring Boot
– Leap Boot: Upload/Import Excel file information into MySQL Database
– Spring Boot: Upload/Import CSV file data into MySQL Database
Deployment: Deploy Spring Boot App on AWS – Elastic Beanstalk
Spring Boot Rest APIs for uploading Files
Our Leap Kicking Awarding will provide APIs for:
- uploading File to a static folder in the Server
- downloading File from server with the link
- getting list of Files' information (file proper noun & url)
These are APIs to exist exported:
| Methods | Urls | Actions |
|---|---|---|
| POST | /upload | upload a File |
| Become | /files | get List of Files (name & url) |
| GET | /files/[filename] | download a File |
This is the static binder that stores all uploaded files:
If you lot desire to store files in database similar this:
Y'all can find teaching at:
Spring Kick Upload/Download File to/from Database example
Engineering
- Coffee 8
- Spring Boot 2 (with Leap Spider web MVC)
- Maven three.six.1
Project Structure
Let me explain information technology briefly.
– FileInfo contains data of the uploaded file.
– FilesStorageService helps us to initialize storage, salve new file, load file, get listing of Files' info, delete all files.
– FilesController uses FilesStorageService to export Remainder APIs: Mail service a file, Become all files' data, download a File.
– FileUploadExceptionAdvice handles exception when the controller processes file upload.
– application.properties contains configuration for Servlet Multipart.
– uploads is the static folder for storing files.
– pom.xml for Spring Boot dependency.
Setup Leap Boot projection
Utilize Leap web tool or your development tool (Jump Tool Suite, Eclipse, Intellij) to create a Leap Boot project.
Then open pom.xml and add these dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-spider web</artifactId> </dependency> Create Service for File Storage
Outset we demand an interface that will be autowired in the Controller.
In service folder, create FilesStorageService interface like following lawmaking:
service/FilesStorageService.coffee
bundle com.bezkoder.bound.files.upload.service; import coffee.nio.file.Path; import coffee.util.stream.Stream; import org.springframework.core.io.Resource; import org.springframework.spider web.multipart.MultipartFile; public interface FilesStorageService { public void init(); public void relieve(MultipartFile file); public Resource load(String filename); public void deleteAll(); public Stream<Path> loadAll(); } Now we create implementation of the interface.
service/FilesStorageServiceImpl.java
package com.bezkoder.spring.files.upload.service; import java.io.IOException; import java.net.MalformedURLException; import coffee.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.web.multipart.MultipartFile; @Service public course FilesStorageServiceImpl implements FilesStorageService { individual terminal Path root = Paths.become("uploads"); @Override public void init() { endeavour { Files.createDirectory(root); } catch (IOException e) { throw new RuntimeException("Could non initialize folder for upload!"); } } @Override public void save(MultipartFile file) { attempt { Files.copy(file.getInputStream(), this.root.resolve(file.getOriginalFilename())); } catch (Exception e) { throw new RuntimeException("Could not store the file. Mistake: " + e.getMessage()); } } @Override public Resource load(String filename) { try { Path file = root.resolve(filename); Resource resource = new UrlResource(file.toUri()); if (resource.exists() || resources.isReadable()) { return resource; } else { throw new RuntimeException("Could not read the file!"); } } catch (MalformedURLException east) { throw new RuntimeException("Error: " + due east.getMessage()); } } @Override public void deleteAll() { FileSystemUtils.deleteRecursively(root.toFile()); } @Override public Stream<Path> loadAll() { endeavour { return Files.walk(this.root, i).filter(path -> !path.equals(this.root)).map(this.root::relativize); } catch (IOException eastward) { throw new RuntimeException("Could not load the files!"); } } } Define Data Models
Permit'southward create FileInfo model which has fields: name & url.
model/FileInfo.coffee
package com.bezkoder.spring.files.upload.model; public form FileInfo { individual String name; private String url; public FileInfo(Cord name, Cord url) { this.proper name = name; this.url = url; } public Cord getName() { render this.name; } public void setName(String proper noun) { this.name = name; } public String getUrl() { render this.url; } public void setUrl(String url) { this.url = url; } } Define Response Message
The ResponseMessage is for bulletin to client that we're gonna use in Rest Controller and Exception Handler.
message/ResponseMessage.coffee
package com.bezkoder.spring.files.upload.message; public class ResponseMessage { private String message; public ResponseMessage(String message) { this.message = message; } public String getMessage() { render message; } public void setMessage(String bulletin) { this.message = message; } } Create Controller for upload & download Files
In controller parcel, we create FilesController.
controller/FilesController.coffee
parcel com.bezkoder.leap.files.upload.controller; import java.util.Listing; import java.util.stream.Collectors; import org.springframework.beans.mill.annotation.Autowired; import org.springframework.core.io.Resources; 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.notation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.spider web.bind.annotation.PathVariable; import org.springframework.spider web.demark.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.note.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; import com.bezkoder.bound.files.upload.model.FileInfo; import com.bezkoder.spring.files.upload.model.ResponseMessage; import com.bezkoder.spring.files.upload.service.FilesStorageService; @Controller @CrossOrigin("http://localhost:8081") public class FilesController { @Autowired FilesStorageService storageService; @PostMapping("/upload") public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file) { String message = ""; try { storageService.salvage(file); bulletin = "Uploaded the file successfully: " + file.getOriginalFilename(); return ResponseEntity.status(HttpStatus.OK).torso(new ResponseMessage(message)); } take hold of (Exception due east) { bulletin = "Could not upload the file: " + file.getOriginalFilename() + "!"; return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message)); } } @GetMapping("/files") public ResponseEntity<List<FileInfo>> getListFiles() { Listing<FileInfo> fileInfos = storageService.loadAll().map(path -> { String filename = path.getFileName().toString(); Cord url = MvcUriComponentsBuilder .fromMethodName(FilesController.grade, "getFile", path.getFileName().toString()).build().toString(); return new FileInfo(filename, url); }).collect(Collectors.toList()); return ResponseEntity.condition(HttpStatus.OK).body(fileInfos); } @GetMapping("/files/{filename:.+}") @ResponseBody public ResponseEntity<Resource> getFile(@PathVariable Cord filename) { Resource file = storageService.load(filename); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "zipper; filename=\"" + file.getFilename() + "\"").body(file); } } – @CrossOrigin is for configuring allowed origins.
– @Controller annotation is used to define a controller.
– @GetMapping and @PostMapping notation is for mapping HTTP Become & Post requests onto specific handler methods:
- Mail /upload:
uploadFile() - GET /files:
getListFiles() - GET /files/[filename]:
getFile()
– We apply @Autowired to inject implementation of FilesStorageService bean to local variable.
Configure Multipart File for Servlet
Let'due south define the maximum file size that tin can be uploaded in application.properties as following:
spring.servlet.multipart.max-file-size=500KB bound.servlet.multipart.max-asking-size=500KB – spring.servlet.multipart.max-file-size: max file size for each asking.
– leap.servlet.multipart.max-request-size: max request size for a multipart/form-information.
Handle File Upload Exception
This is where we handle the case in that a asking exceeds Max Upload Size. The system will throw MaxUploadSizeExceededException and we're gonna use @ControllerAdvice with @ExceptionHandlerannotation for handling the exceptions.
exception/FileUploadExceptionAdvice.java
parcel com.bezkoder.spring.files.upload.exception; import org.springframework.spider web.multipart.MaxUploadSizeExceededException; import org.springframework.spider web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.bezkoder.spring.files.upload.model.ResponseMessage; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class FileUploadExceptionAdvice extends ResponseEntityExceptionHandler { @ExceptionHandler(MaxUploadSizeExceededException.class) public ResponseEntity<ResponseMessage> handleMaxSizeException(MaxUploadSizeExceededException exc) { return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).trunk(new ResponseMessage("File too large!")); } } Initialize Storage
We need to run init() method of FilesStorageService (and also deleteAll() if necessary). So open SpringBootUploadFilesApplication.java and implement CommandLineRunner for run() method like this:
package com.bezkoder.spring.files.upload; import javax.notation.Resource; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.bezkoder.spring.files.upload.service.FilesStorageService; @SpringBootApplication public course SpringBootUploadFilesApplication implements CommandLineRunner { @Resource FilesStorageService storageService; public static void main(Cord[] args) { SpringApplication.run(SpringBootUploadFilesApplication.class, args); } @Override public void run(String... arg) throws Exception { storageService.deleteAll(); storageService.init(); } } Run & Test
Run Bound Kicking application with command: mvn spring-kicking:run.
Refresh the project directory and you will see uploads folder inside it.
Permit's use Postman to brand some requests.
– Upload some files:
– Upload a file with size larger than max file size (500KB):
– Cheque uploads folder:
– Retrieve list of Files' information:
– Now you can download any file from one of the paths above.
For example: http://localhost:8080/files/bezkoder.png.
Conclusion
Today we've learned how to create Spring Boot File Upload Rest Api Application to upload multipart files and go files' data with static binder via Restful API.
Following tutorials explain how to build Front-end Apps to work with our Spring Boot Server:
– Angular 8 Client / Angular ten Customer / Athwart 11 Client / Angular 12
– Athwart Cloth 12
– Vue Customer / Vuetify Customer
– React Client / React Hooks Customer
– Cloth UI Client
– React Paradigm Upload with Preview
– Axios Client
For multiple Files at once:
How to upload multiple files in Java Spring Boot
You tin also know way to upload an Excel/CSV file and shop the content in MySQL database with the mail service:
– Spring Boot: Upload/Import Excel file data into MySQL Database
– Jump Kicking: Upload/Import CSV file data into MySQL Database
If yous want to store files in database like this:
You tin can find pedagogy at:
Leap Boot Upload/Download File to/from Database case
Happy Learning! See you over again.
Further Reading
- Multipart Content-Blazon
Source Lawmaking
You can observe the complete source code for this tutorial on Github.
Source: https://www.bezkoder.com/spring-boot-file-upload/
Post a Comment for "Uploading a File via Rest Call Using Spring Resttemplate"