Skip to content Skip to sidebar Skip to footer

How to Upload a File Using Spring Mvc in Java

In this tutorial, I volition show you lot how to upload and download files to/from database with a Spring Boot Rest APIs. Nosotros likewise use Spring Spider web MultipartFile interface to handle HTTP multi-function requests.

This Spring Boot App works with:
– Angular 8 Customer / Athwart 10 Client / Angular 11 Customer / Angular 12
– Angular Material 12
– Vue Client / Vuetify Client
– React Client / React Hooks Client
– Fabric UI Client
– Axios Client

Related Posts:
– How to upload multiple files in Coffee Spring Boot
– Spring Kick: Upload/Import Excel file data into MySQL Database
– Spring Kick: Upload/Import CSV file data into MySQL Database

Deployment:
– Deploy Spring Kick App on AWS – Rubberband Beanstalk
– Docker Compose: Spring Boot and MySQL example

Spring Boot Residual APIs for uploading Files to Database

Our Spring Kicking Awarding will provide APIs for:

  • uploading File to PostgreSQL/MySQL database
  • downloading File database with the link
  • getting list of Files' information (file name, url, blazon, size)

These are APIs to be exported:

Methods Urls Actions
Mail service /upload upload a File
GET /files become List of Files (name, url, type, size)
Go /files/[fileId] download a File

The uploaded files volition be stored in PostgreSQL/MySQL Database files table with these fields: id, name, type and data as BLOB type (Binary Large Object is for storing binary information like file, epitome, sound, or video).

spring-boot-upload-files-to-database-table-files

Technology

  • Java 8
  • Spring Boot 2 (with Leap Spider web MVC)
  • PostgreSQL/MySQL Database
  • Maven 3.6.1

Project Structure

spring-boot-upload-files-to-database-project-structure

Let me explain information technology briefly.

FileDB is the data model corresponding to files table in database.
FileDBRepository extends Bound Information JpaRepository which has methods to store and retrieve files.
FilesStorageService uses FileDBRepository to provide methods for saving new file, become file by id, get list of Files.
FilesController uses FilesStorageService to export Rest APIs: POST a file, GET all files' information, download a File.
FileUploadExceptionAdvice handles exception when the controller processes file upload.
ResponseFile contains information of the file (name, url, type, size) for HTTP response payload.
application.backdrop contains configuration for Servlet Multipart and PostgreSQL/MySQL database connection.
pom.xml for Spring Boot, Bound Data JPA and PostgreSQL/MySQL connector dependency.

Setup Bound Boot project

Use Jump spider web tool or your evolution tool (Leap Tool Suite, Eclipse, Intellij) to create a Leap Boot projection.

Then open pom.xml and add these dependencies:

          <dependency> 	<groupId>org.springframework.kicking</groupId> 	<artifactId>leap-boot-starter-spider web</artifactId> </dependency> <dependency> 	<groupId>org.springframework.kicking</groupId> 	<artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>                  

Nosotros also demand to add i more than dependency.
– If you desire to use MySQL:

          <dependency> 	<groupId>mysql</groupId> 	<artifactId>mysql-connector-java</artifactId> 	<scope>runtime</scope> </dependency>                  

– or PostgreSQL:

          <dependency> 	<groupId>org.postgresql</groupId> 	<artifactId>postgresql</artifactId> 	<scope>runtime</scope> </dependency>                  

Create Data Model

This Data Model is for storing File Data. There are 4 fields:

  • id: automatically generated every bit UUID
  • proper noun: proper noun of the file
  • type: mime type
  • data: array of bytes, map to a BLOB

model/FileDB.java

          package com.bezkoder.spring.files.upload.db.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(proper noun = "files") public course FileDB {   @Id   @GeneratedValue(generator = "uuid")   @GenericGenerator(name = "uuid", strategy = "uuid2")   private String id;   private String name;   individual String type;   @Lob   individual byte[] data;   public FileDB() {   }   public FileDB(Cord name, String type, byte[] data) {     this.name = proper name;     this.type = type;     this.information = information;   }   public String getId() {     return id;   }   public Cord getName() {     return name;   }   public void setName(Cord proper name) {     this.proper name = proper name;   }   public String getType() {     return type;   }   public void setType(Cord type) {     this.type = blazon;   }   public byte[] getData() {     render data;   }   public void setData(byte[] data) {     this.data = data;   } }                  

In the lawmaking above, data is annotated by @Lob annotation. LOB is datatype for storing big object data. There're two kinds of LOB: BLOB and CLOB:

  • Hulk is for storing binary data
  • CLOB is for storing text data

Create Repository

Under repository package, create FileDBRepository interface that extends JpaRepository.

repository/FileDBRepository.java

          parcel com.bezkoder.bound.files.upload.db.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.bezkoder.bound.files.upload.db.model.FileDB; @Repository public interface FileDBRepository extends JpaRepository<FileDB, String> { }                  

Now we tin can use FileDBRepository with JpaRepository's methods such as: save(FileDB), findById(id), findAll().

Create Service for File Storage

The File Storage Service volition use FileDBRepository to provide following methods:

  • store(file): receives MultipartFile object, transform to FileDB object and salvage it to Database
  • getFile(id): returns a FileDB object by provided Id
  • getAllFiles(): returns all stored files every bit list of code>FileDB objects

service/FileStorageService.java

          packet com.bezkoder.spring.files.upload.db.service; import java.io.IOException; import java.util.stream.Stream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import com.bezkoder.spring.files.upload.db.model.FileDB; import com.bezkoder.spring.files.upload.db.repository.FileDBRepository; @Service public grade FileStorageService {   @Autowired   private FileDBRepository fileDBRepository;   public FileDB store(MultipartFile file) throws IOException {     Cord fileName = StringUtils.cleanPath(file.getOriginalFilename());     FileDB FileDB = new FileDB(fileName, file.getContentType(), file.getBytes());     render fileDBRepository.save(FileDB);   }   public FileDB getFile(String id) {     render fileDBRepository.findById(id).get();   }      public Stream<FileDB> getAllFiles() {     return fileDBRepository.findAll().stream();   } }                  

Ascertain Response Information Classes

Allow's create two classes in message package. The controller will employ these classes for sending message via HTTP responses.

  • ResponseFile: contains name, url, type, size
  • ResponseMessage for notification/data message

message/ResponseFile.coffee

          bundle com.bezkoder.leap.files.upload.db.message; public class ResponseFile {   private String name;   private String url;   private String blazon;   private long size;   public ResponseFile(String name, String url, String type, long size) {     this.name = proper noun;     this.url = url;     this.type = type;     this.size = size;   }   public String getName() {     return name;   }   public void setName(Cord name) {     this.name = name;   }   public Cord getUrl() {     return url;   }   public void setUrl(String url) {     this.url = url;   }   public Cord getType() {     render type;   }   public void setType(String blazon) {     this.type = blazon;   }   public long getSize() {     return size;   }   public void setSize(long size) {     this.size = size;   } }                  

bulletin/ResponseMessage.java

          packet com.bezkoder.spring.files.upload.db.message; public course ResponseMessage {   private String message;   public ResponseMessage(String message) {     this.message = message;   }   public String getMessage() {     return message;   }   public void setMessage(Cord message) {     this.message = message;   } }                  

Create Controller for upload & download Files to Database

In controller package, we create FileController course.

controller/FileController.coffee

          bundle com.bezkoder.bound.files.upload.db.controller; import java.util.List; import coffee.util.stream.Collectors; import org.springframework.beans.manufacturing plant.notation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.note.CrossOrigin; import org.springframework.spider web.bind.note.GetMapping; import org.springframework.web.bind.notation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.demark.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.bezkoder.leap.files.upload.db.service.FileStorageService; import com.bezkoder.spring.files.upload.db.bulletin.ResponseFile; import com.bezkoder.spring.files.upload.db.message.ResponseMessage; import com.bezkoder.spring.files.upload.db.model.FileDB; @Controller @CrossOrigin("http://localhost:8081") public form FileController {   @Autowired   private FileStorageService storageService;   @PostMapping("/upload")   public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file) {     String message = "";     try {       storageService.store(file);       message = "Uploaded the file successfully: " + file.getOriginalFilename();       return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));     } catch (Exception eastward) {       message = "Could not upload the file: " + file.getOriginalFilename() + "!";       return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));     }   }   @GetMapping("/files")   public ResponseEntity<Listing<ResponseFile>> getListFiles() {     List<ResponseFile> files = storageService.getAllFiles().map(dbFile -> {       String fileDownloadUri = ServletUriComponentsBuilder           .fromCurrentContextPath()           .path("/files/")           .path(dbFile.getId())           .toUriString();       return new ResponseFile(           dbFile.getName(),           fileDownloadUri,           dbFile.getType(),           dbFile.getData().length);     }).collect(Collectors.toList());     return ResponseEntity.status(HttpStatus.OK).body(files);   }   @GetMapping("/files/{id}")   public ResponseEntity<byte[]> getFile(@PathVariable String id) {     FileDB fileDB = storageService.getFile(id);     return ResponseEntity.ok()         .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileDB.getName() + "\"")         .trunk(fileDB.getData());   } }                  

@CrossOrigin is for configuring allowed origins.
@Controller annotation is used to define a controller.
@GetMapping and @PostMapping annotation is for mapping HTTP GET & POST requests onto specific handler methods:

  • Mail service /upload: uploadFile()
  • GET /files: getListFiles()
  • Get /files/[id]: getFile()

– We employ @Autowired to inject implementation of FileStorageService bean to local variable.

Configure Spring Datasource, JPA, Hibernate

Under src/master/resource folder, open application.backdrop and write these lines.

– For MySQL:

          spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=simulated spring.datasource.username= root jump.datasource.password= 123456 spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect # Hibernate ddl auto (create, create-driblet, validate, update) spring.jpa.hide.ddl-auto= update                  

– For PostgreSQL:

          spring.datasource.url= jdbc:postgresql://localhost:5432/testdb spring.datasource.username= postgres spring.datasource.password= 123 bound.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true leap.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect # Hibernate ddl auto (create, create-drop, validate, update) leap.jpa.hibernate.ddl-auto= update                  
  • spring.datasource.username & spring.datasource.password properties are the same as your database installation.
  • Spring Boot uses Hide for JPA implementation, nosotros configure MySQL5InnoDBDialect for MySQL or PostgreSQLDialect for PostgreSQL
  • spring.jpa.hibernate.ddl-auto is used for database initialization. We set the value to update value so that a table will be created in the database automatically corresponding to defined data model. Any change to the model volition also trigger an update to the tabular array. For production, this belongings should be validate.

Configure Multipart File for Servlet

Let'southward define the maximum file size that can exist uploaded in application.properties as following:

          bound.servlet.multipart.max-file-size=2MB spring.servlet.multipart.max-asking-size=2MB                  

spring.servlet.multipart.max-file-size: max file size for each request.
spring.servlet.multipart.max-request-size: max request size for a multipart/form-data.

Handle File Upload Exception

This is where nosotros handle the instance in that a request exceeds Max Upload Size. The organisation will throw MaxUploadSizeExceededException and nosotros're gonna use @ControllerAdvice with @ExceptionHandlerannotation for handling the exceptions.

exception/FileUploadExceptionAdvice.coffee

          packet com.bezkoder.spring.files.upload.db.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.spider web.bind.annotation.ControllerAdvice; import org.springframework.web.demark.note.ExceptionHandler; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.bezkoder.jump.files.upload.db.bulletin.ResponseMessage; @ControllerAdvice public form FileUploadExceptionAdvice extends ResponseEntityExceptionHandler {   @ExceptionHandler(MaxUploadSizeExceededException.class)   public ResponseEntity<ResponseMessage> handleMaxSizeException(MaxUploadSizeExceededException exc) {     return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage("File also large!"));   } }                  

Run & Test

Run Spring Kick application with command: mvn bound-kick:run.
Let's use Postman to brand some requests.

– Upload some files:

spring-boot-upload-files-to-database-example

– Upload a file with size larger than max file size (2MB):

spring-boot-upload-files-to-database-upload-large-file-exception

– Cheque files table in Database:

spring-boot-upload-files-to-database-table-files

– Retrieve list of Files' data:

spring-boot-upload-files-to-database-get-list-files

– At present yous can download whatever file from one of the paths above.
For case: http://localhost:8080/files/6ba3578c-ce22-4dd7-999e-72192bf31b53

Decision

Today we've learned how to create Spring Kick Application to upload multipart files and become files' information with static folder via Restful API.

Following tutorials explain how to build Front-terminate Apps to work with our Spring Boot Server:
– Angular 8 Client / Angular 10 Client / Angular 11 Client / Angular 12
– Athwart Material 12
– Vue Client / Vuetify Customer
– React Client / React Hooks Client
– Material UI Client
– Axios Client

You can also know way to upload an Excel/CSV file and store the content in MySQL database with the post:
– Jump Kicking: Upload/Import Excel file data into MySQL Database
– Spring Kick: Upload/Import CSV file data into MySQL Database

Happy Learning! Run into yous over again.

Farther Reading

  • Multipart Content-Blazon
  • How to upload multiple files in Java Spring Boot

Deployment:
– Deploy Spring Kick App on AWS – Elastic Beanstalk
– Docker Etch: Spring Boot and MySQL example

Source Code

You can find the complete source code for this tutorial on Github.

burkealarly.blogspot.com

Source: https://www.bezkoder.com/spring-boot-upload-file-database/

Postar um comentário for "How to Upload a File Using Spring Mvc in Java"