Spring Boot入门教程(二十二): 文件上传

一:文件上传

1. pom.xml

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

2. application.properties

spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.max-file-size=10MB

additional-spring-configuration-metadata.json

{
      "name": "spring.http.multipart.enabled",
      "type": "java.lang.Boolean",
      "description": "Whether to enable support of multipart uploads.",
      "defaultValue": true,
      "deprecation": {
        "replacement": "spring.servlet.multipart.enabled",
        "level": "error"
      }
    },
    {
      "name": "spring.http.multipart.file-size-threshold",
      "type": "java.lang.String",
      "description": "Threshold after which files will be written to disk. Values can use the suffixes\n \"MB\" or \"KB\" to indicate megabytes or kilobytes respectively.",
      "defaultValue": "0",
      "deprecation": {
        "replacement": "spring.servlet.multipart.file-size-threshold",
        "level": "error"
      }
    },
    {
      "name": "spring.http.multipart.location",
      "type": "java.lang.String",
      "description": "Intermediate location of uploaded files.",
      "deprecation": {
        "replacement": "spring.servlet.multipart.location",
        "level": "error"
      }
    },
    {
      "name": "spring.http.multipart.max-file-size",
      "type": "java.lang.String",
      "description": "Max file size. Values can use the suffixes \"MB\" or \"KB\" to indicate megabytes or\n kilobytes respectively.",
      "defaultValue": "1MB",
      "deprecation": {
        "replacement": "spring.servlet.multipart.max-file-size",
        "level": "error"
      }
    },
    {
      "name": "spring.http.multipart.max-request-size",
      "type": "java.lang.String",
      "description": "Max request size. Values can use the suffixes \"MB\" or \"KB\" to indicate megabytes or\n kilobytes respectively.",
      "defaultValue": "10MB",
      "deprecation": {
        "replacement": "spring.servlet.multipart.max-request-size",
        "level": "error"
      }
    },
    {
      "name": "spring.http.multipart.resolve-lazily",
      "type": "java.lang.Boolean",
      "description": "Whether to resolve the multipart request lazily at the time of file or parameter\n access.",
      "defaultValue": false,
      "deprecation": {
        "replacement": "spring.servlet.multipart.resolve-lazily",
        "level": "error"
      }
    }

3. html

upload.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="提交" />
</form>
</body>
</html>

resut.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
</body>
</html>

4. SampleController

@Controller
public class SampleController {
    @GetMapping("/")
    public String upload() {
        return "upload";
    }

    @RequestMapping("/result")
    public String result() {
        return "result";
    }

     @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:result";
        }

        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(uploadDirectory() + "/" + file.getOriginalFilename());
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message",
                     file.getOriginalFilename() + " upload success");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/result";
    }

    private String uploadDirectory() throws FileNotFoundException {
        //获取跟目录
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!path.exists()) path = new File("");
        System.out.println("path:"+path.getAbsolutePath());

        //如果上传目录为/static/images/upload/,则可以如下获取:
        File upload = new File(path.getAbsolutePath(),"static/upload/");
        if(!upload.exists()) upload.mkdirs();
        System.out.println("upload url:"+upload.getAbsolutePath());

        //在开发测试模式时,得到的地址为:{项目跟目录}/target/static/images/upload/
        //在打包成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/

        return upload.getAbsolutePath();
    }
}    

5.访问 localhost:8080/

选择上传文件进行上传

这里写图片描述

这里写图片描述

这里写图片描述


二:热部署

热部署有三种方式:

  • Spring Loaded
  • spring-boot-devtools
  • JRebel 插件

JRebel插件

  1. IDEA安装插件Preferences –> Plugins –> JRebel –> Install(安装时可能由于网络会超时,多尝试几次)

  2. 获取激活码 https://my.jrebel.com –> 登录(没有账号就去注册,需要翻墙,这里是注册facebook)–> try jrebel for free –> 完善资料(注意姓名中的姓和名中间要有一个空格)—> 复制激活码

  3. 重启IDEA, 在Preferences –> JRebel —> 将上步获取到激活码填入到Activation code

  4. idea中最左下侧JRebel Panel –> 选中第一个复选框(JR), 然后单击idea中最上层第一个JR, 如果修改java代码后要先编译一下Command + Shift + F9即可,涉及到页面自己主动刷新页面

注意:JRebel值对java文件变动生效,对静态文件不起作用。使用JRebel启动可能会报错,但不影响功能。
这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

猜你喜欢

转载自blog.csdn.net/vbirdbest/article/details/79788212