Spring > Classic Web services

Guides

POM

Thymeleaf

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project ...">
 
    <!-- ... -->
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
 
    <!-- ... -->
 
</project>

Upload file

src\main\java\hello\Application.java
// ...
@SpringBootApplication
public class Application implements CommandLineRunner {
 
    public static String ROOT = "upload-dir";
 
    public static void main(String[] args) {
	SpringApplication.run(Application.class, args);
    }
 
    @Override
    public void run(String... args) throws Exception {
	new File(ROOT).mkdir();
    }
 
}
src\main\java\hello\FileUploadController.java
// ...
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
 
@Controller
public class FileUploadController {
 
    @RequestMapping(method = RequestMethod.GET, value = "/upload")
    public String provideUploadInfo(Model model) {
	File rootFolder = new File(Application.ROOT);
	model.addAttribute(
		"files",
		Arrays.stream(rootFolder.listFiles()).sorted(Comparator.comparingLong(f -> -1 * f.lastModified()))
			.map(f -> f.getName()).collect(Collectors.toList()));
	return "uploadForm";
    }
 
    @RequestMapping(method = RequestMethod.POST, value = "/upload")
    public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,
	    RedirectAttributes redirectAttributes) {
	String message;
	if (name.contains("/")) {
	    message = "You failed to upload " + name + " folder separators are not allowed";
	} else if (file.isEmpty()) {
	    message = "You failed to upload " + name + " because the file was empty";
	} else {
	    try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(Application.ROOT
		    + "/" + name)))) {
		FileCopyUtils.copy(file.getInputStream(), stream);
		message = "You successfully uploaded " + name + "!";
	    } catch (Exception e) {
		message = "You failed to upload " + name + " => " + e.getMessage();
	    }
	}
	redirectAttributes.addFlashAttribute("message", message);
	return "redirect:upload";
    }
}
  • The entire class is marked up with @Controller so Spring MVC can pick it up and look for routes.
  • Each method is tagged with @RequestMapping to flag the path and the HTTP action.
src\main\resources\templates\uploadForm.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
 
	<div th:if="${message}">
		<h2 th:text="${message}" />
	</div>
 
	<div>
		<form method="POST" enctype="multipart/form-data" action="/upload">
			<table>
				<tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
				<tr><td>Name:</td><td><input type="text" name="name" /></td></tr>
				<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
			</table>
		</form>
	</div>
 
	<div>
		<ul>
			<li th:each="file : ${files}" th:text="${file}" />
		</ul>
	</div>
 
</body>
</html>
  • As part of auto-configuring Spring MVC, Spring Boot will create a MultipartConfigElement bean and make itself ready for file uploads. Here's how to configure it:
src\main\resources\application.properties
multipart.maxFileSize=128KB
Print/export