spring boot(七)文件上传

版权声明:菜鸟_zhengke的博客 https://blog.csdn.net/qq_42014192/article/details/89093973

1.新建一个springboot项目

https://blog.csdn.net/qq_42014192/article/details/88742559

2.引入相关依赖

<!--thymeleaf模板引擎-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--devtools-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

3.修改启动类

@SpringBootApplication
public class SpringbootScwjDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootScwjDemoApplication.class, args);
    }
    
    //tomcatEmbedded 这段代码是为了解决,上传文件大于10M出现连接重置的问题。此异常内容 GlobalException 也捕获不到。
    @Bean
    public TomcatServletWebServerFactory tomcatEmbedded() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
            if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
                //-1 means unlimited
                ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
            }
        });
        return tomcat;
    }
}

4.application.properties设置相关上传属性

#http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties
#search multipart
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

5.新建前端界面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="Submit" />
</form>
</body>
</html>

6.新建controller上传异常检测类

@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 异常检测
     * @param e
     * @param redirectAttributes
     * @return
     */
    @ExceptionHandler(MultipartException.class)
    public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
        redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
        return "redirect:/uploadStatus";
    }
}

7.创建文件上传控制层

@Controller
public class UploadControllerTest {

    /**
     * 指定项目根路径
     */
    private static String UPLOADED_FOLDER = "E://temp//";
    @GetMapping("/")
    public String index(){
        return "upload";
    }

    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file")MultipartFile file, RedirectAttributes redirectAttributes){
        //判断文件是否纯在,判断是否为空
        if (file.isEmpty()){
            redirectAttributes.addFlashAttribute("message","请选择要上载的文件");
            return "redirect:uploadStatus";
        }
        try {
            // 获取文件以字节数组保存,并将其设置到某个位置
            byte[] bytes = file.getBytes();
            Path path = Paths.get( UPLOADED_FOLDER +file.getOriginalFilename());
            //文件拷贝
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message", "您已成功上载 '" + file.getOriginalFilename() + "'");
        }catch (IOException e){
            e.printStackTrace();
        }
        return "redirect:/uploadStatus";
    }
    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "uploadStatus";
    }
}

8.创建上传文件状态后的界面提示

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

猜你喜欢

转载自blog.csdn.net/qq_42014192/article/details/89093973