springboot文件上传 学习总结(三)

这是一个简单的文件上传的例子,view用的是freemarker,为的是传递数据方便,用起来跟html差不多。

首先创建一个springboot项目,没创建的可以看我上一篇文档(链接)

1、首先目录结构如下

springboot文件上传 学习总结(三)_第1张图片

2、pon.xml文件如下



    4.0.0

    com.example
    testdemo
    0.0.1-SNAPSHOT
    jar

    testdemo
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.9.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.springframework.boot
            spring-boot-devtools
            true
        

        
            org.springframework.boot
            spring-boot-starter-freemarker
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



3、接下来是两个Controller文件

(1)UploadController类

package com.example.testdemo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@Controller
public class UploadController {
    //上传的路径
    private static String UPLOADED_FOLDER = "E:\\";

    @GetMapping("/")
    public ModelAndView index() {
        return new ModelAndView("upload");
    }

    @PostMapping("/upload")
    public ModelAndView singleFileUpload(@RequestParam("file") MultipartFile file,
                                         Map map) {
        if (file.isEmpty()) {
            map.put("msg", "您未选择所需上传的文件");
            map.put("url", "/");
            return new ModelAndView("error", map);
        }
        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
            map.put("msg", "成功上传文件:"+file.getOriginalFilename());
            map.put("url", "/");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ModelAndView("success", map);
    }
}

(2)GlobalExceptionHandler类

package com.example.testdemo.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@ControllerAdvice
public class GlobalExceptionHandler {

    //https://jira.spring.io/browse/SPR-14651
    //4.3.5 supports RedirectAttributes redirectAttributes
    @ExceptionHandler(MultipartException.class)
    public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
        redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
        return "redirect:/uploadStatus";
    }
}

4、启动类的代码如下

import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class TestdemoApplication {

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

    @Bean
    public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
            if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol)) {
                //-1 means unlimited
                ((AbstractHttp11Protocol) connector.getProtocolHandler()).setMaxSwallowSize(-1);
            }
        });
        return tomcat;
    }
}

5、三个view文件

(1)error.ftl



    
    错误信息
    


错误!

${msg},3s后自动跳转

(2)success.ftl



    
    成功提示
    


成功!

${msg!""},3s后自动跳转

(3)upload.ftl





Spring Boot file upload example



6、最后是配置文件application.properties

  设置可以上传的文件大小的上限

spring.http.multipart.max-file-size=30MB
spring.http.multipart.max-request-size=30MB

最后启动项目,访问http://localhost:8080/即可

 

你可能感兴趣的:(SpringBoot)