Spring Boot File Upload Example With Jsp
Bound Boot Rest API File Upload/Save Example
This guide shows y'all how to upload/salvage a file using Bound Boot Residue API. To upload files via HTTP multi-office requests volition be handled by MultipartFile
. Information technology is a representation of an uploaded file received in a multipart request through which we tin get the file contents and stored in the database or file system.
P.S. Tested on Windows environs.
What we'll build
We will create a Spring Boot spider web awarding that accepts the file uploads and salvage files into the database or file system location.
Similar Posts:
- Jump Kick- Display prototype from database and classpath
- How to insert image in database using Spring MVC
- How to fetch data from database in Spring MVC
Applied science Used
Find the listing of all technologies used in this awarding.
- Bound Tool Suite iv
- JDK 8
- Spring Boot 2.2.iv.RELEASE
- Spring Data JPA ii.2.4.RELEASE
- MySQL Database
- Maven 3
Dependencies Required
These the basic dependencies that required in this application, add together them to your pom.xml.
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-four.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>org.websparrow</groupId> <artifactId>spring-kick-upload-file</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <java.version>ane.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-information-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-kick-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-coffee</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </projection>
ane. Save in the File System
To salvage/re-create/upload file in the system directory, follow the beneath steps;
- Get the bytes of the file which comes in HTTP multi-function asking by calling
getBytes()
method ofMultipartFile
interface. It returns the byte array of the file. - Set up the path (directory location) where yous want to relieve/copy/upload the file.
getOriginalFilename()
method return original proper name of file. - Write byte array to the desired location via
Files.write(path, bytes);
@PostMapping("/directory") public String uploadToDirectory(@RequestParam MultipartFile file) throws IOException { byte[] bytes = file.getBytes(); Path path = Paths.get(DIR_TO_UPLOAD + file.getOriginalFilename()); Files.write(path, bytes); return "File uploaded"; }
2. Salve in the Database
Similarly, we can save the multi-office form data into the database table. We just need to have care of the column definition where we insert the file.
2.1 Entity
Suppose, we want to save id, name and profile photo of Prime Minister of India, and so the entity class will look like:
PrimeMinisterOfIndia.java
package org.websparrow.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Tabular array; @Entity @Table public grade PrimeMinisterOfIndia implements Serializable { individual static concluding long serialVersionUID = 2842598520185366295L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; @Lob private byte[] photograph; // Generate Getters and Setters... }
Why
@Lob
note used here? Because when want to store large dataset/file object into the database table, we demand huge space. LOB stands for Big OBject and the maximum chapters of a LOB is (four gigabytes-1) bytes.It will result the following SQL definition.
CREATE TABLE `prime_minister_of_india` ( `id` int(11) NOT Nothing AUTO_INCREMENT, `name` varchar(255) DEFAULT Cypher, `photo` longblob, PRIMARY Key (`id`) );
two.two Repository
FileUploadRepository.java
package org.websparrow.repository; import org.springframework.information.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.websparrow.entity.PrimeMinisterOfIndia; @Repository public interface FileUploadRepository extends JpaRepository<PrimeMinisterOfIndia, Integer> { }
2.3 Controller
The first step is the same we discussed above:
- Get the
bytes
of the file. - Set the HTTP multi-part form information to an entity.
- Call the
save(Entity eastward)
method of the Leap InformationJpaRepository
interface.
@PostMapping(value = "/database") public Cord uploadToDatabase(@RequestParam String proper name, @RequestParam MultipartFile file) throws IOException { // Set the grade information into entity PrimeMinisterOfIndia pmOfIndia = new PrimeMinisterOfIndia(); pmOfIndia.setName(name); pmOfIndia.setPhoto(file.getBytes()); // Salvage the records into the database fileUploadRepository.salve(pmOfIndia); render "Records saved into database."; }
Here is the consummate controller class which caters the both 1. Upload file to classpath/organization directory and 2. Inter the grade data and file into the database table.
FileUploadController.java
package org.websparrow.controller; import java.io.IOException; import coffee.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.beans.factory.notation.Autowired; import org.springframework.web.bind.notation.PostMapping; import org.springframework.web.bind.notation.RequestMapping; import org.springframework.spider web.demark.annotation.RequestParam; import org.springframework.web.demark.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.websparrow.entity.PrimeMinisterOfIndia; import org.websparrow.repository.FileUploadRepository; @RestController @RequestMapping("/upload/file") public grade FileUploadController { @Autowired private FileUploadRepository fileUploadRepository; private static terminal Cord DIR_TO_UPLOAD = "C:\\Users\\Atul\\Desktop\\sparrow\\"; @PostMapping(value = "/database") public String uploadToDatabase(@RequestParam String name, @RequestParam MultipartFile file) throws IOException { // Ready the class data into entity PrimeMinisterOfIndia pmOfIndia = new PrimeMinisterOfIndia(); pmOfIndia.setName(proper name); pmOfIndia.setPhoto(file.getBytes()); // Save the records into the database fileUploadRepository.relieve(pmOfIndia); return "Records saved into database."; } @PostMapping("/directory") public String uploadToDirectory(@RequestParam MultipartFile file) throws IOException { byte[] bytes = file.getBytes(); Path path = Paths.become(DIR_TO_UPLOAD + file.getOriginalFilename()); Files.write(path, bytes); render "File uploaded"; } }
Run the application
TheSpringBootUploadFileAppication
class contains the main method and responsible to offset the application.
SpringBootUploadFileApplication.coffee
package org.websparrow; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootUploadFileApplication { public static void main(Cord[] args) { SpringApplication.run(SpringBootUploadFileApplication.form, args); } }
Exam the awarding
Allow'due south test the application, executing the in a higher place class and it volition showtime the awarding so follow the below steps:
- Open the Postman client, select the HTTP Postal service method, enter your endpoint in the accost bar.
- Click on the Body tab and check the grade-information. Fill the data in primal-value pair. And for file, select the file blazon from the dropdown list.
- Hit the Send push button.
References
- Spring Boot- Uploading Files
- How to insert epitome in database using Spring MVC
- How to fetch image from database using Jump MVC
- Binary large object- Wikipedia
Source: https://www.websparrow.org/spring/spring-boot-rest-api-file-upload-save-example
0 Response to "Spring Boot File Upload Example With Jsp"
Post a Comment