Javascript required
Skip to content Skip to sidebar Skip to footer

Java 8 Client Secure File Upload Tutorial

Through this tutorial, I will guide yous how to code file upload functionality in a Java spider web application based on Jump Boot, Leap Information JPA and Thymeleaf.

Prerequisite: You got familiar with Jump Boot form treatment and Spring Information JPA.

Suppose that we have an existing Spring Boot project that includes the user direction module. Now we want to update the lawmaking to allow the admin to upload photos for users. The create user grade would look like this:

create user form

This form, besides text fields, allows the user to pick a file (profile photos) from local computer and when he clicks Save, the file volition 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 paradigm 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 cavalcade that stores the file name. Say, the column proper name is photos :

users table

The data type is varchar(64) so the column can store file name containing up to 64 characters. So we demand to update corresponding entity class User as follows:

@Entity @Table(name = "users") public class User { 	 	@Column(nullable = true, length = 64) 	private Cord photos;  	// other fields and getters, setters are not shown	 }

And no updates required for the UserRepository grade.

two. Update Web Form for File Upload

Adjacent, we need to update the create new user form to add together a file input equally follows:

<course th:action="@{/users/salvage}"  	thursday:object="${user}" method="mail" 	enctype="multipart/grade-information" 	> 	... 	<div> 	 	<label>Photos: </characterization> 	<input blazon="file" name="image" take="image/png, prototype/jpeg" /> 	 	</div> 	... </form>

Note that nosotros must set the attribute enctype="multipart/form-information" form the form tag, to tell the browser that this form may incorporate file upload. And we restrict that only paradigm files can be uploaded using the have aspect:

<input type="file" name="image" accept="paradigm/png, image/jpeg" />

In case you desire to let uploading any files, do not use this attribute.

iii. Update Leap Controller to Handle File Upload

On the server side with Spring Boot, we demand to update the handler method that is responsible to handle form submission every bit follows:

@Controller public form UserController {  	@Autowired  	private UserRepository repo; 	 	@PostMapping("/users/relieve") 	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);  		Cord uploadDir = "user-photos/" + savedUser.getId();  		FileUploadUtil.saveFile(uploadDir, fileName, multipartFile); 		 		return new RedirectView("/users", true); 	} }

To handle file uploaded from the customer, we demand to declare this parameter for the handler method:

@RequestParam("prototype") MultipartFile multipartFile

The @RequestParam note and MultipartFile interface come from the following packages:

import org.springframework.web.demark.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile;

That means nosotros don't have to apply any external library for handling file upload. Simply use the spring starter web dependency is enough. Under the hood, Bound will apply 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:

Cord fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename()); user.setPhotos(fileName); User savedUser = service.salvage(user);

The class StringUtils come from the package org.springframework.util. Note that we store only the file proper name in the database table, and the bodily uploaded file is stored in the file system:

Cord 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 application'due south directory. And beneath is the code of the FileUploadUtil form:

package net.codejava;  import coffee.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); 		}		 	} }

Every bit yous 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 arrangement.

4. Display uploaded images in browser

In instance of uploaded files are images, we can display the images in browser with a piddling configuration. We need to betrayal the directory containing the uploaded files so the clients (spider web browsers) tin 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.spider web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;  @Configuration public form MvcConfig implements WebMvcConfigurer {   	@Override 	public void addResourceHandlers(ResourceHandlerRegistry registry) { 		exposeDirectory("user-photos", registry); 	} 	 	private void exposeDirectory(String dirName, ResourceHandlerRegistry registry) { 		Path uploadDir = Paths.go(dirName); 		Cord uploadPath = uploadDir.toFile().getAbsolutePath(); 		 		if (dirName.startsWith("../")) dirName = dirName.supersede("../", ""); 		 		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 application's context path as /user-photos.

Add together a new getter in the entity class User every bit follows:

@Entity public grade User { 	@Transient 	public String getPhotosImagePath() { 		if (photos == null || id == nil) render zip; 		 		return "/user-photos/" + id + "/" + photos; 	} }

Then in the view (HTML with Thymeleaf), we can display an epitome like this:

<img th:src="/@{${user.photosImagePath}}" />

That's how to implement file upload functionality for an existing Jump Boot application. And in case of images, y'all learned how to brandish the images in the browser. To summarize, here are the primal points:

  • Add a column to store file name in the database table.
  • Declare a field in the entity grade to store name of the uploaded file.
  • Use file input in the web grade and set attribute enctype="multipart/course-information" for the form tag.
  • Use @RequestParam and MultipartFile in Spring controller's handler method.
  • Use Files.re-create() method to copy the uploaded file from temporary location to a stock-still directory in the file arrangement.
  • Configure Spring MVC to betrayal 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:

Related Tutorials:

  • Spring Boot Upload Multiple Files Instance

Other Spring Boot Tutorials:

  • Leap Boot Consign Data to CSV Example
  • Jump Kick Howdy Earth Case
  • Spring Boot automated restart using Spring Boot DevTools
  • Spring Boot Form Handling Tutorial with Leap Form Tags and JSP
  • How to create a Spring Boot Spider web Awarding (Spring MVC with JSP/ThymeLeaf)
  • Spring Boot - Spring Data JPA - MySQL Example
  • Spring Boot Hi World RESTful Web Services Tutorial
  • How to use JDBC with Spring Boot
  • Spring Boot CRUD Web Awarding with JDBC - Thymeleaf - Oracle
  • Spring Boot RESTful CRUD API Examples with MySQL database
  • How to package Spring Kicking application to JAR and War
  • Jump Boot Security Authentication with JPA, Hibernate and MySQL
  • Spring Information JPA Paging and Sorting Examples
  • Leap Kick Fault Handling Guide

Well-nigh the Author:

Nam Ha Minh is certified Java developer (SCJP and SCWCD). He started programming with Java in the fourth dimension of Java one.4 and has been falling in love with Java since then. Brand friend with him on Facebook and sentry his Coffee videos yous YouTube.

Add comment

coppinruchey.blogspot.com

Source: https://www.codejava.net/frameworks/spring-boot/spring-boot-file-upload-tutorial