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> <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入门——文件上传与下载的更多相关文章
- Java Web 学习(8) —— Spring MVC 之文件上传与下载
Spring MVC 之文件上传与下载 上传文件 表单: <form action="upload" enctype="multipart/form-data&qu ...
- spring boot:单文件上传/多文件上传/表单中多个文件域上传(spring boot 2.3.2)
一,表单中有多个文件域时如何实现说明和文件的对应? 1,说明和文件对应 文件上传页面中,如果有多个文件域又有多个相对应的文件说明时, 文件和说明如何对应? 我们在表单中给对应的file变量和text变 ...
- Spring MVC的文件上传和下载
简介: Spring MVC为文件上传提供了直接的支持,这种支持使用即插即用的MultipartResolver实现的.Spring MVC 使用Apache Commons FileUpload技术 ...
- 0062 Spring MVC的文件上传与下载--MultipartFile--ResponseEntity
文件上传功能在网页中见的太多了,比如上传照片作为头像.上传Excel文档导入数据等 先写个上传文件的html <!DOCTYPE html> <html> <head&g ...
- Spring MVC-学习笔记(5)spring MVC的文件上传、下载、拦截器
1.文件上传. spring MVC为文件上传提供了直接的支持,这种支持是即插即用的MultipartResolver(多部分解析器)实现的.spring MVC使用Apache Commo ...
- 使用Spring MVC实现文件上传与下载
前段时间做毕业设计的时候,想要完成一个上传文件的功能,后来,虽然在自己本地搭建了一个ftp服务器,然后使用公司的工具完成了一个文档管理系统:但是还是没有找到自己想要的文件上传与下载的方式. 今天看到一 ...
- spring boot实现文件上传下载
spring boot 引入”约定大于配置“的概念,实现自动配置,节约了开发人员的开发成本,并且凭借其微服务架构的方式和较少的配置,一出来就占据大片开发人员的芳心.大部分的配置从开发人员可见变成了相对 ...
- Spring Boot 教程 - 文件上传下载
在日常的开发工作中,基本上每个项目都会有各种文件的上传和下载,大多数文件都是excel文件,操作excel的JavaAPI我用的是apache的POI进行操作的,POI我之后会专门讲到.此次我们不讲如 ...
- 基于Spring MVC的文件上传和下载功能的实现
配置文件中配置扫描包,以便创建各个类的bean对象 <context:component-scan base-package="com.neuedu.spring_mvc"& ...
随机推荐
- Vue.Js加入bootstrap及jquery,或加入其他插件vue-resource,vuex等
.引入jquery 项目目录下输入 cnpm install jquery --save-dev 用npm下载jq依赖 若想加入其他js库,如vue-resource,执行命令cnpm in ...
- php下载解决中文乱码问题
利用 iconv() 函数解决乱码 $file_name = iconv("utf-8","gb2312",$file_name); 具体下载代码如下: pub ...
- Javascript-闰年javascript的判断
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- yii2中关联查询
yii2 ActiveRecord多表关联以及多表关联搜索的实现 一个老生常谈的问题.最近通过群里的反馈,觉得很多人还是没有去理解这个问题.今天把这个问题讲明白了,看看yii2 ActiveRecor ...
- 十图详解tensorflow数据读取机制
在学习tensorflow的过程中,有很多小伙伴反映读取数据这一块很难理解.确实这一块官方的教程比较简略,网上也找不到什么合适的学习材料.今天这篇文章就以图片的形式,用最简单的语言,为大家详细解释一下 ...
- Azkaban 简介
本文简单介绍一下Azkaban及其特点.azkaban是一个开源的任务调度系统,用于负责任务的调度运行(如数据仓库调度),用以替代linux中的crontab. 一.Azkaban是什么? 1.1 A ...
- Linux命令: 向文件写内容,编辑文件,保存文件,查看文件,不保存文件
1.找到要编辑的文件 2.敲 vi t1.txt ,显示文件内容(vim命令) 3.敲 i,最下面变成INSERT 4.编辑自己想要的内容 5a.敲ESC:wq回车 5b.如果不想保存文件在时敲ES ...
- Struts2 Spring Hibernate 框架整合 Annotation MavenProject
项目结构目录 pom.xml 添加和管理jar包 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns ...
- Linux启动vi编辑器时提示E325: ATTENTION解决方案
Linux启动vi编辑器时提示E325: ATTENTION解决方案 Vi编辑器是Linux的文本编辑器,在Linux系统的运用非常广泛,不少朋友在打开Vi编辑器的时候提示E325: ATTENTIO ...
- 阿里云实现简单的运行 Django 项目
首先申请一个阿里云账号,买一个阿里云服务器是必须的,对于一个学生来讲,按道理说,在不打折不搞活动的时候,价格还是蛮贵的,所以说,同志们,革命尚未成功,一定要挺住!!! 申请了阿里云,消费完毕,登录阿里 ...