Spring Boot Tutorial (27) Receiving uploaded multi-file files

build project

For example to create a springmvc project you need spring-boot-starter-thymeleaf and spring-boot-starter-web starter dependencies. For example, to upload files to the server, you need to add tags in web.xml to do related configuration, but in the sringboot project, it has been done automatically for you, so you don't need to do any configuration.

  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

Create file upload controller

Paste the code directly:

@Controller
public class FileUploadController {

    private final StorageService storageService;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {

        model.addAttribute("files", storageService
                .loadAll()
                .map(path ->
                        MvcUriComponentsBuilder
                                .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                                .build().toString())
                .collect(Collectors.toList()));

        return "uploadForm";
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

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

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

        storageService.store(file);
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + file.getOriginalFilename() + "!");

        return "redirect:/";
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }

}

This class is annotated with @Controller, indicating that it is the c of the last Spring mvc. Each method is 
annotated with @GetMapping or @PostMapping to indicate its own http method.

  • GET / Get the list of uploaded files
  • GET /files/{filename} download a file that already exists on the server
  • POST / upload file to server

Create a simple html template

In order to show the process of uploading files, we make an interface: 
in 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="/">
            <table>
                <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>
            </table>
        </form>
    </div>

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

</body>
</html>

Upload file size limit

If you need to limit the size of the uploaded file, it is also very simple, just add the following to the src/main/resources/application.properties of the springboot project:

spring.http.multipart.max-file-size=128KB
spring.http.multipart.max-request-size=128KB

 

source code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325510764&siteId=291194637