Spring Boot (30) 上传文件
文件上传
上传文件和下载文件是Java Web中常见的一种操作,文件上传主要是将文件通过IO流传输到服务器的某一个文件夹下。
导入依赖
在pom.xml中添加上spring-boot-starter-web和spring-boot-starter-thymeleaf的依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
配置文件
默认情况下SPring Boot无需做任何配置也能实现文件上传的功能,但有可能因默认配置不符而导致文件上传失败问题,所以了解相关配置信息更有助于我们对问题的定位和修复。
spring:
#禁用thymeleaf缓存
thymeleaf:
cache: false
servlet:
multipart:
#是否支持批量上传(默认true)
enabled: true
#上传文件的临时目录(一般不用修改)
location:
max-file-size: 1048576
#上传请求最大为10M(默认10M)
max-request-size: 10485760
#文件大小阀值,当大于这个阀值时将写入到磁盘,否则存在内存中(默认值0 一般不用修改)
file-size-threshold: 0
#判断是否要延迟解析文件(相当于懒加载 一般不用修改)
resolve-lazily: false
如果只允许1M以下的文件,当超出该范围则会抛出以下错误
org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException:
the request was rejected because its size (20738021) exceeds the configured maximum (10485760)
上传页面
在src/main/resources下新建static,在static中新建一个index.html的模板文件,实现单文件上传、多文件上传、BASE64编码三种上传方式,其中BASE64的方式在对Android/IOS/H5等方面还是不错的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body> <h2>单一文件上传示例</h2>
<div>
<form method="POST" enctype="multipart/form-data" action="/uploads/upload1">
<p>
文件1:<input type="file" name="file"/>
<input type="submit" value="上传"/>
</p>
</form>
</div> <hr/>
<h2>批量文件上传示例</h2> <div>
<form method="POST" enctype="multipart/form-data" action="/uploads/upload2">
<p>
文件1:<input type="file" name="file"/>
</p>
<p>
文件2:<input type="file" name="file"/>
</p>
<p>
<input type="submit" value="上传"/>
</p>
</form>
</div> <hr/>
<h2>Base64文件上传</h2>
<div>
<form method="POST" action="/uploads/upload3">
<p>
BASE64编码:<textarea name="base64" rows="10" cols="80"></textarea>
<input type="submit" value="上传"/>
</p>
</form>
</div> </body>
</html>
控制层
创建一个FileUploadController,其中@GetMapping的方式用来跳转index.html页面,而@PostMapping相关方法则是对应的单文件上传、多文件上传、BASE64编码三种方式
@Request("file")此处的file对应的就是html中的name="file"的input标签,而将文件真正写入的还是借助的commons-io中的FileUtils.copyInputStreamToFile(inputStream,file)
package com.spring.boot.controller; import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
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; import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; @Controller
@RequestMapping("/uploads")
public class FileUploadController { @PostMapping("/upload1")
@ResponseBody
public Map<String,String> upload1(@RequestParam("file")MultipartFile imgFile,HttpServletRequest request) throws IOException {
// 获取文件名
String fileName = imgFile.getOriginalFilename();
// 获取图片后缀
String extName = fileName.substring(fileName.lastIndexOf("."));
if(extName.equals(".jpg")){
// 自定义的文件名称
String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
// 设置存放图片文件的路径
String path="/Users/baidawei/Downloads/imgUpload/" +trueFileName;
// 开始上传
imgFile.transferTo(new File(path));
} Map<String, String> result = new HashMap<>(16);
result.put("contentType", imgFile.getContentType());
result.put("fileName", imgFile.getOriginalFilename());
result.put("fileSize", imgFile.getSize() + "");
return result;
} @PostMapping("/upload2")
@ResponseBody
public List<Map<String,String>> upload2(@RequestParam("file") MultipartFile [] files) throws IOException {
if(files ==null || files.length == 0){
return null;
} List<Map<String,String>> results = new ArrayList<>(); for(MultipartFile file : files){
String path="/Users/baidawei/Downloads/imgUpload/" + file.getOriginalFilename();
file.transferTo(new File(path)); Map<String, String> map = new HashMap<>(16);
map.put("contentType", file.getContentType());
map.put("fileName", file.getOriginalFilename());
map.put("fileSize", file.getSize() + "");
results.add(map);
}
return results;
} @PostMapping("/upload3")
@ResponseBody
public void upload3(String base64) throws IOException {
// TODO BASE64 方式的 格式和名字需要自己控制(如 png 图片编码后前缀就会是 data:image/png;base64,)
final File tempFile = new File("/Users/baidawei/Downloads/imgUpload/test.jpg");
// TODO 防止有的传了 data:image/png;base64, 有的没传的情况
String[] d = base64.split("base64,");
final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]);
FileCopyUtils.copy(bytes,tempFile);
} }
启动项目进行测试:
http://localhost:8088/
上传单个返回:
{"fileName":"sunwukong.jpg","fileSize":"199556","contentType":"image/jpeg"}
上传多个图片 返回:
[{"fileName":"狮子头.jpg","fileSize":"187554","contentType":"image/jpeg"},{"fileName":"mh1.jpg","fileSize":"260842","contentType":"image/jpeg"}]
Base64编码转换地址:http://base64.xpcha.com/pic.html
需要先把图片转换为base64编码后 再上传
Spring Boot (30) 上传文件的更多相关文章
- spring boot(十七)上传文件
上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例. 1.pom包配置 我们使用Spring Boot最新版本1.5.9. ...
- Spring Boot应用上传文件时报错
问题描述 Spring Boot应用(使用默认的嵌入式Tomcat)在上传文件时,偶尔会出现上传失败的情况,后台报错日志信息如下:"The temporary upload location ...
- 使用Spring boot + jQuery上传文件(kotlin)
文件上传也是常见的功能,趁着周末,用Spring boot来实现一遍. 前端部分 前端使用jQuery,这部分并不复杂,jQuery可以读取表单内的文件,这里可以通过formdata对象来组装键值对, ...
- Spring框架学习笔记(7)——Spring Boot 实现上传和下载
最近忙着都没时间写博客了,做了个项目,实现了下载功能,没用到上传,写这篇文章也是顺便参考学习了如何实现上传,上传和下载做一篇笔记吧 下载 主要有下面的两种方式: 通过ResponseEntity实现 ...
- Spring Boot:上传文件大小超限制如何捕获 MaxUploadSizeExceededException 异常
Spring Boot 默认上传文件大小限制是 1MB,默认单次请求大小是 10MB,超出大小会跑出 MaxUploadSizeExceededException 异常 spring.servlet. ...
- spring mvc(注解)上传文件的简单例子
spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...
- Android+Spring Boot 选择+上传+下载文件
2021.02.03更新 1 概述 前端Android,上传与下载文件,使用OkHttp处理请求,后端使用Spring Boot,处理Android发送来的上传与下载请求.这个其实不难,就是特别多奇奇 ...
- RestTemplate OR Spring Cloud Feign 上传文件
SpringBoot,通过RestTemplate 或者 Spring Cloud Feign,上传文件(支持多文件上传),服务端接口是MultipartFile接收. 将文件的字节流,放入ByteA ...
- spring boot file上传
用Spring Boot写读取Excel文件小工具的时候遇到的一些小坑已经填平,复制即可满足普通的文件上传功能POI方面只需一个包,其他通用包工程中一般都会带TIPS:前端为了扩展我用ajax异步请求 ...
随机推荐
- SVN的配置与使用方法
1.所选服务器安装包:VisualSVN-Server-2.1.3.msi. 2.客户端安装包:TortoiseSVN-1.6.2.16344-win32-svn-1.6.2.msi 一.服务器的安装 ...
- 再探gdb经常使用命令
前面已经有了一篇对gdb经常使用命令的总结.见 http://blog.csdn.net/u011848617/article/details/12838875 这里对眼下学过的gdb命令进行了 ...
- 破碎纪念---记第二次Nexus4换屏
四太子的屏幕太易碎了.去年九月份在美国买的,十月便碎了,十二月修好,前几天又摔碎了. 本着对此机的喜爱,今天就进行了第二次换屏. 用同事的话说,如今已经是熟练工种了. 先来看看破碎景象: 右下角破碎, ...
- Echarts 如何使用 bmap 的 API
使用 Echarts 在绘制 Binning on map 的图形时(其实也就是 在地图上绘制热力色块图) 解决因为数据量过大,希望在拖拽加载或者缩放加载的时候,根据可视区域的经纬度范围,来请求相应的 ...
- UVA10056 - What is the Probability ?(概率)
UVA10056 - What is the Probability ? (概率) 题目链接 题目大意:有n个人玩游戏,一直到一个人胜出之后游戏就能够结束,要不然就一直从第1个到第n个循环进行,没人一 ...
- [英语学习]微软面试前英语集训笔记-day 1
最近有机会参加微软面试前的英语集训. 第一天是由wendy老师主讲.热场题目是介绍你自己.包括你的姓名,家庭hobby,爱好,专业,学校,工作经历等等. 接下来的主题是friendship.给我印象较 ...
- c# WinForm的一些问题
工作中,用WinForm写了一段程序,刚开始运行正常,后来替换为公司框架的时候,发现原来用Label拼的表格控件,里面的Text无法显示,后来发现,父控件的ForColor为Control导致,子空间 ...
- the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers.
the largest value you actually can transmit between the client and server is determined by the amoun ...
- 纯css3实现美化复选框和手风琴效果(详细)
关键技术点和原理: 原理就是把 checkbox或 radio 给隐藏掉 ,然后给选框 绑定一个label标签. 然后用label标签作为容器,在里面放一个:before或一个after 用bef ...
- ios18---自定义控件3改进
控制器: // XMGViewController.h #import <UIKit/UIKit.h> @interface XMGViewController : UIViewContr ...