Spring Boot file upload only pdf



CodeJava
Coding Your Passion
  • Home>
  • Frameworks>
  • Spring Boot
Learn Spring framework:

  • Learn Spring on YouTube

  • Understand the core of Spring

  • Understand Spring MVC

  • Understand Spring AOP

  • Understand Spring Data JPA

  • Spring Dependency Injection (XML)

  • Spring Dependency Injection (Annotations)

  • Spring Dependency Injection (Java config)

  • Spring MVC beginner tutorial

  • Spring MVC Exception Handling

  • Spring MVC and log4j

  • Spring MVC Send email

  • Spring MVC File Upload

  • Spring MVC Form Handling

  • Spring MVC Form Validation

  • Spring MVC File Download

  • Spring MVC JdbcTemplate

  • Spring MVC CSV view

  • Spring MVC Excel View

  • Spring MVC PDF View

  • Spring MVC XstlView

  • Spring MVC + Spring Data JPA + Hibernate - CRUD

  • Spring MVC Security (XML)

  • Spring MVC Security (Java config)

  • Spring & Hibernate Integration (XML)

  • Spring & Hibernate Integration (Java config)

  • Spring & Struts Integration (XML)

  • Spring & Struts Integration (Java config)

  • 14 Tips for Writing Spring MVC Controller



Spring Boot File Upload Tutorial (Upload and Display Images)

DetailsWritten by Nam Ha MinhLast Updated on 20 September 2020 | Print Email


Through this tutorial, I will guide you how to code file upload functionality in a Java web application based on Spring Boot, Spring Data JPA and Thymeleaf.Prerequisite: You got familiar with Spring Boot form handling and Spring Data JPA.Suppose that we have an existing Spring Boot project that includes the user management module. Now we want to update the code to allow the admin to upload photos for users. The create user form would look like this:
Spring Boot file upload only pdf
This form, besides text fields, allows the user to pick a file (profile photos) from local computer and when he clicks Save, the file will be uploaded to the server and stored in a separate directory. The name of the file is stored in the database. And you will also learn how to display the uploaded image file in the browser.

1. Update Database table and for Entity class

We need to update the users table in the database, adding a new column that stores the file name. Say, the column name is photos:
Spring Boot file upload only pdf
The data type is varchar(64) so the column can store file name containing up to 64 characters. Then we need to update corresponding entity class User as follows:@Entity @Table(name = "users") public class User { @Column(nullable = true, length = 64) private String photos; // other fields and getters, setters are not shown }


And no updates required for the UserRepository class.

2. Update Web Form for File Upload

Next, we need to update the create new user form to add a file input as follows:<form th:action="@{/users/save}" th:object="${user}" method="post" enctype="multipart/form-data" > ... <div> <label>Photos: </label> <input type="file" name="image" accept="image/png, image/jpeg" /> </div> ... </form>Note that we must set the attribute enctype=multipart/form-data form the form tag, to tell the browser that this form may contain file upload. And we restrict that only image files can be uploaded using the accept attribute:<input type="file" name="image" accept="image/png, image/jpeg" />In case you want to allow uploading any files, do not use this attribute.

3. Update Spring Controller to Handle File Upload

On the server side with Spring Boot, we need to update the handler method that is responsible to handle form submission as follows:@Controller public class UserController { @Autowired private UserRepository repo; @PostMapping("/users/save") public RedirectView saveUser(User user, @RequestParam("image") MultipartFile multipartFile) throws IOException { String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename()); user.setPhotos(fileName); User savedUser = repo.save(user); String uploadDir = "user-photos/" + savedUser.getId(); FileUploadUtil.saveFile(uploadDir, fileName, multipartFile); return new RedirectView("/users", true); } }To handle file uploaded from the client, we need to declare this parameter for the handler method:@RequestParam("image") MultipartFile multipartFileThe @RequestParam annotation and MultipartFile interface come from the following packages:import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile;That means we dont have to use any external library for handling file upload. Just use the spring starter web dependency is enough. Under the hood, Spring will use Apache Commons File Upload that parses multipart request to reads data from the file uploaded.Next, we get the name of the uploaded file, set it to the photos field of the User object, which is then persisted to the database:String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename()); user.setPhotos(fileName); User savedUser = service.save(user);The class StringUtils come from the package org.springframework.util. Note that we store only the file name in the database table, and the actual uploaded file is stored in the file system:String uploadDir = "user-photos/" + savedUser.getId(); FileUploadUtil.saveFile(uploadDir, fileName, multipartFile);Here, the uploaded file is stored in the directory user-photos/userID, which is relative to the applications directory. And below is the code of the FileUploadUtil class:package net.codejava; import java.io.*; import java.nio.file.*; import org.springframework.web.multipart.MultipartFile; public class FileUploadUtil { public static void saveFile(String uploadDir, String fileName, MultipartFile multipartFile) throws IOException { Path uploadPath = Paths.get(uploadDir); if (!Files.exists(uploadPath)) { Files.createDirectories(uploadPath); } try (InputStream inputStream = multipartFile.getInputStream()) { Path filePath = uploadPath.resolve(fileName); Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException ioe) { throw new IOException("Could not save image file: " + fileName, ioe); } } }As you can see, this utility class is only responsible for creating the directory if not exists, and save the uploaded file from MultipartFile object to a file in the file system.

4. Display uploaded images in browser

In case of uploaded files are images, we can display the images in browser with a little configuration. We need to expose the directory containing the uploaded files so the clients (web browsers) can access. Create a configuration file with the following code:package net.codejava; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { exposeDirectory("user-photos", registry); } private void exposeDirectory(String dirName, ResourceHandlerRegistry registry) { Path uploadDir = Paths.get(dirName); String uploadPath = uploadDir.toFile().getAbsolutePath(); if (dirName.startsWith("../")) dirName = dirName.replace("../", ""); registry.addResourceHandler("/" + dirName + "/**").addResourceLocations("file:/"+ uploadPath + "/"); } }Here, we configure Spring MVC to allow access to the directory user-photos in the file system, with mapping to the applications context path as /user-photos.Add a new getter in the entity class User as follows:@Entity public class User { @Transient public String getPhotosImagePath() { if (photos == null || id == null) return null; return "/user-photos/" + id + "/" + photos; } }Then in the view (HTML with Thymeleaf), we can display an image like this:<img th:src="/@{${user.photosImagePath}}" />Thats how to implement file upload functionality for an existing Spring Boot application. And in case of images, you learned how to display the images in the browser. To summarize, here are the key points:
  • Add a column to store file name in the database table.
  • Declare a field in the entity class to store name of the uploaded file.
  • Use file input in the web form and set attribute enctype=multipart/form-data for the form tag.
  • Use @RequestParam and MultipartFile in Spring controllers handler method.
  • Use Files.copy() method to copy the uploaded file from temporary location to a fixed directory in the file system.
  • Configure Spring MVC to expose the upload directory so image files can show up in the browser.
If you want to see the coding in action, I recommend you to watch the video below:
  • Spring Boot Upload Multiple Files Example

Other Spring Boot Tutorials:

  • Spring Boot Export Data to CSV Example
  • Spring Boot Hello World Example
  • Spring Boot automatic restart using Spring Boot DevTools
  • Spring Boot Form Handling Tutorial with Spring Form Tags and JSP
  • How to create a Spring Boot Web Application (Spring MVC with JSP/ThymeLeaf)
  • Spring Boot - Spring Data JPA - MySQL Example
  • Spring Boot Hello World RESTful Web Services Tutorial
  • How to use JDBC with Spring Boot
  • Spring Boot CRUD Web Application with JDBC - Thymeleaf - Oracle
  • Spring Boot RESTful CRUD API Examples with MySQL database
  • How to package Spring Boot application to JAR and WAR
  • Spring Boot Security Authentication with JPA, Hibernate and MySQL
  • Spring Data JPA Paging and Sorting Examples
  • Spring Boot Error Handling Guide

About the Author:

Spring Boot file upload only pdf
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

Notify me of follow-up comments

Send
Cancel

Comments

12345678
#37Andre2022-01-29 19:53
Hi Nam I'm having the same error I can't show the images in the browser, Does this code still work or do you have to make any modifications?
Quote
#36Nam2022-01-13 19:23
Hi Lộc,
Just remove the first / before @. Somehow it was added by the CMS software - it was not there intentionally.
Quote
#35Nguyễn Hữu Lộc2022-01-13 08:31
mình có sử dụng đoạn code trên để show ảnh lên nhưng bị lỗi, bạn hướng dẫn mình được ko?

Caused by: org.attoparser.ParseException: Could not parse as expression: "/@{${user.photosImagePath}}" (template: "user" - line 46, col 8)
Quote
#34randhir Kumar2021-12-24 22:47
This is so bad if I need different path then how I will manage it will not work
Quote
#33Kácio de Sousa Menes2021-12-16 07:24
Hello, could you send me the code of this project to my email please

kacio.sousa
Spring Boot file upload only pdf
gmail.com
Quote
12345678
Refresh comments list