Upload files to project spring boot [closed]


I would like to know how I can store files uploaded by form within the static directory of a spring boot project.

asked by berni10 26.08.2016 в 00:46

1 answer


in Spring there is a tutorial that deals specifically with that, you can also find the implementation in GitHub

You can see the details in the links that I indicated, but the main thing is to make a controller that manages the upload of files:

public class FileUploadController {

private final StorageService storageService;

public FileUploadController(StorageService storageService) {
    this.storageService = storageService;

public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService
            .map(path ->
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())

    return "uploadForm";

public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

    Resource file = storageService.loadAsResource(filename);
    return ResponseEntity
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFilename()+"\"")

public String handleFileUpload(@RequestParam("file") MultipartFile file,
                               RedirectAttributes redirectAttributes) {

            "You successfully uploaded " + file.getOriginalFilename() + "!");

    return "redirect:/";

public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) {
    return ResponseEntity.notFound().build();


A form that serves as an interface for the user and that calls the previously created driver:

<html xmlns:th="http://www.thymeleaf.org">

<div th:if="${message}">
    <h2 th:text="${message}"/>

    <form method="POST" enctype="multipart/form-data" action="/">
            <tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
            <tr><td></td><td><input type="submit" value="Upload" /></td></tr>

        <li th:each="file : ${files}">
            <a th:href="${file}" th:text="${file}" />

and an executable class

public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);

CommandLineRunner init(StorageService storageService) {
    return (args) -> {
answered by 13.10.2016 в 13:14