Spring Boot入门——文件上传与下载

1、在 pom.xml 文件中添加依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

<groupId>com.wyl</groupId>
<artifactId>SpringBootFile</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>SpringBootFile</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
</properties>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
</parent>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
&lt;/dependency&gt;

&lt;!-- thymeleaf模板插件 --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;
&lt;/dependency&gt;

&lt;!-- devtools插件,热部署 --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;
    &lt;optional&gt;<span style="color: rgba(0, 0, 255, 1)">true</span>&lt;/optional&gt;
    &lt;scope&gt;<span style="color: rgba(0, 0, 255, 1)">true</span>&lt;/scope&gt;
&lt;/dependency&gt;

</dependencies>
</project>

2、application.properties 文件中取消模板文件缓存

spring.thymeleaf.cache=false

3、编写模板文件

file.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta charset="UTF-8" /> <title>Insert title here</title> </head> <body> <h1 th:inlines="text"> 文件上传 </h1> <form action="fileUpload"method="post"enctype="multipart/form-data"> <p> 选择文件: <input type="file" name="fileName"/></p> <p><input type="submit" value="提交"/></p> </form> </body> </html>
multifile.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
    <h1 th:inlines="text"> 文件上传 </h1>
    <form action="multifileUpload" method="post" enctype="multipart/form-data" >
        <p> 选择文件 1: <input type="file" name="
fileName"/></p>
        <p> 选择文件 2: <input type="file" name="fileName"/></p>
        <p> 选择文件 3: <input type="file" name="fileName"/></p>
        <p><input type="submit" value="提交"/></p>
    </form>
</body>
</html>

4、编写 Controller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">
 * 获取file.html页面
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
@RequestMapping(</span>"<span style="color: rgba(255, 0, 0, 1)">file</span>"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String file(){
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> "/file"<span style="color: rgba(0, 0, 0, 1)">;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 实现文件上传
 * </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
@RequestMapping(</span>"<span style="color: rgba(255, 0, 0, 1)">fileUpload</span>"<span style="color: rgba(0, 0, 0, 1)">)
@ResponseBody 
</span><span style="color: rgba(0, 0, 255, 1)">public</span> String fileUpload(@RequestParam("fileName"<span style="color: rgba(0, 0, 0, 1)">) MultipartFile file){
    </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)">(file.isEmpty()){
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> "false"<span style="color: rgba(0, 0, 0, 1)">;
    }
    String fileName </span>=<span style="color: rgba(0, 0, 0, 1)"> file.getOriginalFilename();
    </span><span style="color: rgba(0, 0, 255, 1)">int</span> size = (<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)">) file.getSize();
    System.out.println(fileName </span>+ "--&gt;" +<span style="color: rgba(0, 0, 0, 1)"> size);
    
    String path </span>= "F:/test"<span style="color: rgba(0, 0, 0, 1)"> ;
    File dest </span>= <span style="color: rgba(0, 0, 255, 1)">new</span> File(path + "/" +<span style="color: rgba(0, 0, 0, 1)"> fileName);
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(!dest.getParentFile().exists()){ <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">判断文件父目录是否存在</span>

dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
//保存文件
return "true";
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}

  /*
     * 获取 multifile.html 页面
     */
    @RequestMapping("multifile")
    public String multifile(){
        return "/multifile";
    }
    
    /**
     * 实现多文件上传
     * */
    @RequestMapping(value="multifileUpload",method=RequestMethod.POST)

  /**public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files) */
    public @ResponseBody String multifileUpload(HttpServletRequest request){
        
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
        
        if(files.isEmpty()){
            return "false";
        }
        String path = "F:/test" ;
        
        for(MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);
            
            if(file.isEmpty()){
                return "false";
            }else{        
                File dest = new File(path + "/" + fileName);
                if(!dest.getParentFile().exists()){ // 判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                }catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return "false";
                }
            }
        }
        return "true";
    } }

5、测试

 

  

6、多文件上传中遇到的问题

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field fileName exceeds its maximum permitted size of 1048576 bytes.

Spring Boot 默认文件上传大小为 2M,多文档上传中总是出现文件大小超出限度

解决方法:

a、在 application.properties 文件中设置文件大小

# Single file max size  
multipart.maxFileSize=50Mb
# All files max size  
multipart.maxRequestSize=50Mb

  但是,事实证明此种方法不能够解决以上问题

b、在启动类 App.class 文件中配置 Bean 来设置文件大小

import javax.servlet.MultipartConfigElement;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**

  • Hello world!

*/
@SpringBootApplication
@Configuration
public class App
{
public static void main(String[] args )
{
System.out.println(
"Hello World!" );
SpringApplication.run(App.
class, args);
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">  
 * 文件上传配置  
 * </span><span style="color: rgba(128, 128, 128, 1)">@return</span>  
 <span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(255, 0, 0, 1)">  
@Bean  
public MultipartConfigElement multipartConfigElement() {  
    MultipartConfigFactory factory = new MultipartConfigFactory();  
    //单个文件最大  
    factory.setMaxFileSize("10240KB"); //KB,MB  
    /// 设置总上传数据总大小  
    factory.setMaxRequestSize("102400KB");  
    return</span></span><span style="color: rgba(255, 0, 0, 1)"><span style="font-size: 13px"> factory.createMultipartConfig();  
} </span> </span></pre>

7、文件下载

@RequestMapping("download")
    public String downLoad(HttpServletResponse response){
        String filename="2.jpg";
        String filePath = "F:/test" ;
        File file = new File(filePath + "/" + filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
        <span style="color: rgba(0, 0, 255, 1)">byte[] buffer = <span style="color: rgba(0, 0, 255, 1)">new <span style="color: rgba(0, 0, 255, 1)">byte[1024<span style="color: rgba(0, 0, 0, 1)">];
        FileInputStream fis = <span style="color: rgba(0, 0, 255, 1)">null; <span style="color: rgba(0, 128, 0, 1)">//<span style="color: rgba(0, 128, 0, 1)">文件输入流
        BufferedInputStream bis = <span style="color: rgba(0, 0, 255, 1)">null<span style="color: rgba(0, 0, 0, 1)">;
        
        OutputStream os = <span style="color: rgba(0, 0, 255, 1)">null; <span style="color: rgba(0, 128, 0, 1)">//<span style="color: rgba(0, 128, 0, 1)">输出流
        <span style="color: rgba(0, 0, 255, 1)">try<span style="color: rgba(0, 0, 0, 1)"> {
            os =<span style="color: rgba(0, 0, 0, 1)"> response.getOutputStream();
            fis = <span style="color: rgba(0, 0, 255, 1)">new<span style="color: rgba(0, 0, 0, 1)"> FileInputStream(file); 
            bis = <span style="color: rgba(0, 0, 255, 1)">new<span style="color: rgba(0, 0, 0, 1)"> BufferedInputStream(fis);
            <span style="color: rgba(0, 0, 255, 1)">int i =<span style="color: rgba(0, 0, 0, 1)"> bis.read(buffer);
            <span style="color: rgba(0, 0, 255, 1)">while(i != -1<span style="color: rgba(0, 0, 0, 1)">){
                os.write(buffer);
                i =<span style="color: rgba(0, 0, 0, 1)"> bis.read(buffer);
            }
            
        } <span style="color: rgba(0, 0, 255, 1)">catch<span style="color: rgba(0, 0, 0, 1)"> (Exception e) {
            <span style="color: rgba(0, 128, 0, 1)">//<span style="color: rgba(0, 128, 0, 1)"> TODO Auto-generated catch block

e.printStackTrace();
}
System.out.println("----------file download" + filename);
try {
bis.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}