上传文件Uploading Files

你需要什么

  • 大约15分钟
  • IntelliJ IDEA或其他编辑器
  • JDK 1.8或更高版本
  • Maven 3.2+

你会建立什么

您将创建一个接受文件上传的Spring Boot Web应用程序。您还将构建一个简单的HTML界面来上传测试文件。

构建步骤

1、添加maven依赖。

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

2、创建一个上传控制器。


import java.io.IOException;
import java.util.stream.Collectors;

import com.sqlb.guide.uploadingfiles.storage.StorageFileNotFoundException;
import com.sqlb.guide.uploadingfiles.storage.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


@Controller
public class FileUploadController {

    private final StorageService storageService;

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

    /** 查找上传文件的当前列表并将其加载到Thymeleaf模板中。它使用MvcUriComponentsBuilder计算到实际资源的链接   */
    @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";
    }

    /**  如果资源存在,则加载资源,并使用“Content-Disposition”响应头将其发送到浏览器进行下载  */
    @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);
    }

     /** 适用于处理multi-part message file并将其交给StorageService进行保存   */
    @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();
    }

}

这个类是用@Controller注解的,所以Spring MVC可以把它拿起来寻找路由。每个方法都使用 @GetMapping@PostMapping 进行标记,以将路径和HTTP操作绑定到特定的Controller操作。

同时,你需要新建一个StorageService,以及它的实现类FileSystemStorageService,还有一些辅助类,具体可以看 这里

3、新建HTML模板uploadForm.html

<!DOCTYPE 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>

4、application.properties配置一把上传文件参数。

# 文件总大小不能超过128KB
spring.servlet.multipart.max-file-size=128KB

# 整个 multipart/form-data 请求大小不能超过128KB。
spring.servlet.multipart.max-request-size=128KB

spring.http.multipart.enabled=false

5、要启动Spring Boot MVC应用程序,我们首先需要一个启动器。


import com.sqlb.guide.uploadingfiles.storage.StorageProperties;
import com.sqlb.guide.uploadingfiles.storage.StorageService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

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

    /** 启动应用上下文后执行 */
    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();  //创建保存上传文件的路径
        };
    }
}

作为自动配置Spring MVC的一部分,Spring Boot将创建一个MultipartConfigElement bean并为文件上传做好准备。

测试结果

上传完成后 ,结果如下:

原文地址 https://spring.io/guides/gs/uploading-files/

猜你喜欢

转载自blog.csdn.net/she_lock/article/details/80577434