原文地址: https://www.cnblogs.com/studyDetail/p/7003253.html

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> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- 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>
<scope>true</scope>
</dependency> </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 { /*
* 获取file.html页面
*/
@RequestMapping("file")
public String file(){
return "/file";
} /**
* 实现文件上传
* */
@RequestMapping("fileUpload")
@ResponseBody
public String fileUpload(@RequestParam("fileName") MultipartFile file){
if(file.isEmpty()){
return "false";
}
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size); String path = "F:/test" ;
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
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);
} /**
* 文件上传配置
* @return
*/
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件最大
factory.setMaxFileSize("10240KB"); //KB,MB
/// 设置总上传数据总大小
factory.setMaxRequestSize("102400KB");
return factory.createMultipartConfig();
}

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); byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null; OutputStream os = null; //输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
} } catch (Exception e) {
// 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;
}

Spring Boot 文件上传与下载的更多相关文章

  1. spring boot文件上传、下载

    主题:Spring boot 文件上传(多文件上传)[从零开始学Spring Boot]http://www.iteye.com/topic/1143595 Spring MVC实现文件下载http: ...

  2. 从.Net到Java学习第十篇——Spring Boot文件上传和下载

    从.Net到Java学习系列目录 图片上传 Spring Boot中的文件上传就是Spring MVC中的文件上传,将其集成进来了. 在模板目录创建一个新的页面 profile/uploadPage. ...

  3. Spring框架学习笔记(7)——Spring Boot 实现上传和下载

    最近忙着都没时间写博客了,做了个项目,实现了下载功能,没用到上传,写这篇文章也是顺便参考学习了如何实现上传,上传和下载做一篇笔记吧 下载 主要有下面的两种方式: 通过ResponseEntity实现 ...

  4. Spring Boot 文件上传原理

    首先我们要知道什么是Spring Boot,这里简单说一下,Spring Boot可以看作是一个框架中的框架--->集成了各种框架,像security.jpa.data.cloud等等,它无须关 ...

  5. Spring Boot 文件上传简易教程

    上传文件是我们日常使用最为广泛的功能之一,比如App端上传头像.本章演示如何从客户端上传到 Spring Boot 开发的 Api中. 本项目源码 github 下载 1 新建 Spring Boot ...

  6. Spring Boot 文件上传

    其实网上已经有很多这样的文章了.为什么我还要记录一下呢?原因是在工作中对接外系统时,碰到了他们调取我们文件上传接口确存在着http请求头部规范的情况,从而导致用传统方法获取不到参数.今天就来整理下Sp ...

  7. spring boot 文件上传大小限制

    错误信息 : Spring Boot:The field file exceeds its maximum permitted size of 1048576 bytes. 解决方法一:在启动类添加如 ...

  8. (29)Spring boot 文件上传(多文件上传)【从零开始学Spring Boot】

    文件上传主要分以下几个步骤: (1)新建maven java project: (2)在pom.xml加入相应依赖: (3)新建一个表单页面(这里使用thymleaf); (4)编写controlle ...

  9. spring boot 文件上传工具类(bug 已修改)

    以前的文件上传都是之前前辈写的,现在自己来写一个,大家可以看看,有什么问题可以在评论中提出来. 写的这个文件上传是在spring boot 2.0中测试的,测试了,可以正常上传,下面贴代码 第一步:引 ...

随机推荐

  1. mybatis中的增删改查操作

    在这一个部分,主要进行增删改查的示例书写. 增删改查可以基于xml的,也可以基于注解的方式. 一:对单条数据的查询 1.目录结构 这个使得目录更加清晰 2.User.java 这个使用以前的user表 ...

  2. 002.etcd使用场景

    引用链接: https://blog.csdn.net/linuxheik/article/details/77853119 https://www.cnblogs.com/doscho/p/6221 ...

  3. WIN10下使用Anaconda配置opencv、tensorflow、pygame并在pycharm中运用

    昨天想运行一段机器学习的代码,在win10系统下配置了一天的python环境,真的是头疼,准备写篇博客来帮助后面需要配置环境的兄弟. 1.下载Anaconda 根据昨天的经历,发现Anaconda真的 ...

  4. CSS3利用一个div实现内圆角边框效果

    *首先要清楚的是,box-shadow的形状会随着border-radius变化.下面的例子可以证明: <!doctype html> <html lang="en&quo ...

  5. Jmeter脚本录制方法(一)分别使用Badboy录制和Jmeter自带的代理服务器录制

    Jmeter录制方式分三种,分别是:使用Badboy录制.Jmeter自带的代理服务器录制和手工录制,今天先介绍前两种录制方法. Badboy录制 Badboy是用C++开发的动态应用测试工具, 其拥 ...

  6. 无法在web服务器上启动调试,iis未列出与打开的URL匹配的网站

    错误的原因可能是:在iis的网站上绑定的具体的机器的ip地址. 解决方法:可以在网站上绑定ip地址时选择“全部未分配”项.

  7. VSCode换行符

    如果要显示换行符:\r\n 如果要替换显示出来的\n,替换上要用正则表达式,然后使用\r\n. 如果要直接换行,\n

  8. Windows 7重启后USB 3.0无法使用的问题解决

    1.首先对主板USB3.0驱动程序进行重新安装 2.如果驱动程序重装后还是无法解决无法使用USB3.0设备的话,在win7桌面上找到“计算机”图标并鼠标右键,选择“管理”选项,找到设备管理器,然后找到 ...

  9. 使用Apache commons-codec Base64实现加解密(转)

    commons-codec是Apache下面的一个加解密开发包 官方地址为:http://commons.apache.org/codec/ 官方下载地址:http://commons.apache. ...

  10. POJ 2546 &amp; ZOJ 1597 Circular Area(求两圆相交的面积 模板)

    题目链接: POJ:http://poj.org/problem? id=2546 ZOJ:problemId=597" target="_blank">http: ...