SpringBoot实现文件上传功能详解
利用SpirngBoot实现文件上传功能
零、本篇要点
- 介绍SpringBoot对文件上传的自动配置。
- 介绍MultipartFile接口。
- 介绍SpringBoot+Thymeleaf文件上传demo的整合。
- 介绍对文件类型,文件名长度等判断方法。
一、SpringBoot对文件处理相关自动配置
自动配置是SpringBoot为我们提供的便利之一,开发者可以在不作任何配置的情况下,使用SpringBoot提供的默认设置,如处理文件需要的MultipartResolver。
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class })
@ConditionalOnProperty(prefix = "spring.servlet.multipart", name = "enabled", matchIfMissing = true)
@ConditionalOnWebApplication(type = Type.SERVLET)
@EnableConfigurationProperties(MultipartProperties.class)
public class MultipartAutoConfiguration {
private final MultipartProperties multipartProperties;
public MultipartAutoConfiguration(MultipartProperties multipartProperties) {
this.multipartProperties = multipartProperties;
}
@Bean
@ConditionalOnMissingBean({ MultipartConfigElement.class, CommonsMultipartResolver.class })
public MultipartConfigElement multipartConfigElement() {
return this.multipartProperties.createMultipartConfig();
}
@Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
@ConditionalOnMissingBean(MultipartResolver.class)
public StandardServletMultipartResolver multipartResolver() {
StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily());
return multipartResolver;
}
}
- Spring3.1之后支持
StandardServletMultipartResolver,且默认使用StandardServletMultipartResolver,它的优点在于:使用Servlet所提供的功能支持,不需要依赖任何其他的项目。 - 想要自动配置生效,需要配置
spring.servlet.multipart.enabled=true,当然这个配置默认就是true。 - 相关的配置设置在
MultipartProperties中,其中字段就是对应的属性设置,经典字段有:enabled:是否开启文件上传自动配置,默认开启。location:上传文件的临时目录。maxFileSize:最大文件大小,以字节为单位,默认为1M。maxRequestSize:整个请求的最大容量,默认为10M。fileSizeThreshold:文件大小达到该阈值,将写入临时目录,默认为0,即所有文件都会直接写入磁盘临时文件中。resolveLazily:是否惰性处理请求,默认为false。
- 我们也可以自定义处理的细节,需要实现MultipartResolver接口。
二、处理上传文件MultipartFile接口
SpringBoot为我们提供了MultipartFile强大接口,让我们能够获取上传文件的详细信息,如原始文件名,内容类型等等,接口内容如下:
public interface MultipartFile extends InputStreamSource {
String getName(); //获取参数名
@Nullable
String getOriginalFilename();//原始的文件名
@Nullable
String getContentType();//内容类型
boolean isEmpty();
long getSize(); //大小
byte[] getBytes() throws IOException;// 获取字节数组
InputStream getInputStream() throws IOException;//以流方式进行读取
default Resource getResource() {
return new MultipartFileResource(this);
}
// 将上传的文件写入文件系统
void transferTo(File var1) throws IOException, IllegalStateException;
// 写入指定path
default void transferTo(Path dest) throws IOException, IllegalStateException {
FileCopyUtils.copy(this.getInputStream(), Files.newOutputStream(dest));
}
}
三、SpringBoot+Thymeleaf整合demo
1、编写控制器
/**
* 文件上传
*
* @author Summerday
*/
@Controller
public class FileUploadController {
private static final String UPLOADED_FOLDER = System.getProperty("user.dir");
@GetMapping("/")
public String index() {
return "file";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) throws IOException {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("msg", "文件为空,请选择你的文件上传");
return "redirect:uploadStatus";
}
saveFile(file);
redirectAttributes.addFlashAttribute("msg", "上传文件" + file.getOriginalFilename() + "成功");
redirectAttributes.addFlashAttribute("url", "/upload/" + file.getOriginalFilename());
return "redirect:uploadStatus";
}
private void saveFile(MultipartFile file) throws IOException {
Path path = Paths.get(UPLOADED_FOLDER + "/" + file.getOriginalFilename());
file.transferTo(path);
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
}
2、编写页面file.html
<html xmlns:th="http://www.thymeleaf.org">
<!--suppress ALL-->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传界面</title>
</head>
<body>
<div>
<form method="POST" enctype="multipart/form-data" action="/upload">
<table>
<tr><td><input type="file" name="file" /></td></tr>
<tr><td></td><td><input type="submit" value="上传" /></td></tr>
</table>
</form>
</div>
</body>
</html>
3、编写页面uploadStatus.html
<!--suppress ALL-->
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传界面</title>
</head>
<body>
<div th:if="${msg}">
<h2 th:text="${msg}"/>
</div>
<div >
<img src="" th:src="${url}" alt="">
</div>
</body>
</html>
4、编写配置
server.port=8081
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
5、配置虚拟路径映射
这一步是非常重要的,我们将文件上传到服务器上时,我们需要将我们的请求路径和服务器上的路径进行对应,不然很有可能文件上传成功,但访问失败:
@Configuration
public class MvcConfig implements WebMvcConfigurer {
private static final String UPLOADED_FOLDER = System.getProperty("user.dir");
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:///" + UPLOADED_FOLDER + "/");
}
}
对应关系需要自己去定义,如果访问失败,可以试着打印以下路径,看看是否缺失了路径分隔符。
注意:如果addResourceHandler不要写成处理/**,这样会拦截掉其他的请求
6、测试页面
执行mvn spring-boot:run,启动程序,访问http://localhost:8081/,选择文件,点击上传按钮,我们的项目目录下出现了mongo.jpg,并且页面也成功显示:

四、SpringBoot的Restful风格,返回url
/**
* 文件上传
*
* @author Summerday
*/
@RestController
public class FileUploadRestController {
/**
* 文件名长度
*/
private static final int DEFAULT_FILE_NAME_LENGTH = 100;
/**
* 允许的文件类型
*/
private static final String[] ALLOWED_EXTENSIONS = {
"jpg", "img", "png", "gif"
};
/**
* 项目路径
*/
private static final String UPLOADED_FOLDER = System.getProperty("user.dir");
@PostMapping("/restUpload")
public Map<String,Object> singleFileUpload(@RequestParam("file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
throw new Exception("文件为空!");
}
String filename = upload(file);
String url = "/upload/" + filename;
Map<String,Object> map = new HashMap<>(2);
map.put("msg","上传成功");
map.put("url",url);
return map;
}
/**
* 上传方法
*/
private String upload(MultipartFile file) throws Exception {
int len = file.getOriginalFilename().length();
if (len > DEFAULT_FILE_NAME_LENGTH) {
throw new Exception("文件名超出限制!");
}
String extension = getExtension(file);
if(!isValidExtension(extension)){
throw new Exception("文件格式不正确");
}
// 自定义文件名
String filename = getPathName(file);
// 获取file对象
File desc = getFile(filename);
// 写入file
file.transferTo(desc);
return filename;
}
/**
* 获取file对象
*/
private File getFile(String filename) throws IOException {
File file = new File(UPLOADED_FOLDER + "/" + filename);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
if(!file.exists()){
file.createNewFile();
}
return file;
}
/**
* 验证文件类型是否正确
*/
private boolean isValidExtension(String extension) {
for (String allowedExtension : ALLOWED_EXTENSIONS) {
if(extension.equalsIgnoreCase(allowedExtension)){
return true;
}
}
return false;
}
/**
* 此处自定义文件名,uuid + extension
*/
private String getPathName(MultipartFile file) {
String extension = getExtension(file);
return UUID.randomUUID().toString() + "." + extension;
}
/**
* 获取扩展名
*/
private String getExtension(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
return originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
}
}
五、源码下载
本文内容均为对优秀博客及官方文档总结而得,原文地址均已在文中参考阅读处标注。最后,文中的代码样例已经全部上传至Gitee:https://gitee.com/tqbx/springboot-samples-learn,另有其他SpringBoot的整合哦。
六、参考阅读
SpringBoot实现文件上传功能详解的更多相关文章
- iOS 的 Safari 文件上传功能详解
iOS 6 给 Safari 浏览器带来的另外一个功能是文件上传,终于 Safari 终于支持 input 输入框的文件类型了,并且还支持 HTML媒体捕获(HTML Media Capture). ...
- Struts2+Uploadify文件上传使用详解
Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示.不过官方提供的实例是php版本的,本文将详细介绍Uploadify在java中的使用,您也可以点击下面的链接进行演示或下 ...
- Web应用安全之文件上传漏洞详解
什么是文件上传漏洞 文件上传漏洞是在用户上传了一个可执行的脚本文件,本通过此脚本文件获得了执行服务器端命令的功能,这种攻击方式是最为直接,最为有效的,有时候,几乎没有什么门槛,也就是任何人都可以进行这 ...
- php文件上传原理详解(含源码)
1.文件上传原理 将客户端的文件上传到服务器,再将服务器的临时文件上传到指定目录 2.客户端配置 提交表单 表单的发送方式为post 添加enctype="multipart/form-da ...
- jquery组件WebUploader文件上传用法详解
这篇文章主要为大家详细介绍了jquery组件WebUploader文件上传用法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 WebUploader是由Baidu WebFE(FEX)团队开发的一 ...
- FastDFS的配置、部署与API使用解读(8)FastDFS多种文件上传接口详解(转)
1.StorageClient与StorageClient1的区别 相信使用happy_fish的FastDFS的童鞋们,一定都熟悉StorageClient了,或者你熟悉的是StorageClien ...
- ASP.Net大文件上传组件详解
首先右键单击网站根目录,在弹出的快捷菜单中,选择"添加引用"菜单项,弹出"添加引用",切换到"浏览"找到组件的Dll文件"Best ...
- [js高手之路]深入浅出webpack教程系列2-配置文件webpack.config.js详解(上)
[js高手之路]深入浅出webpack教程系列索引目录: [js高手之路]深入浅出webpack教程系列1-安装与基本打包用法和命令参数 [js高手之路]深入浅出webpack教程系列2-配置文件we ...
- SpringBoot系列(十二)过滤器配置详解
SpringBoot(十二)过滤器详解 往期精彩推荐 SpringBoot系列(一)idea新建Springboot项目 SpringBoot系列(二)入门知识 springBoot系列(三)配置文件 ...
随机推荐
- linux 内核参数设置 - sysctl
sysctl 命令用于查看和修改内核参数 查看指定参数: sysctl kernel.threads-max 查看所有参数: sysctl -a 修改指定参数: sysctl -w kernel.th ...
- 技术分享丨华为鲲鹏架构Redis知识二三事
摘要:华为云鲲鹏Redis,业界首个基于自研ARM-Based全栈整合的Redis云服务,支持双机热备的HA架构,提供单机.主备.Proxy集群.Cluster集群实例类型,满足高读写性能场景及弹性变 ...
- ThreadLocal什么时候会出现OOM的情况?为什么?
ThreadLocal里面使用了一个存在弱引用的map,当释放掉threadlocal的强引用以后,map里面的value却没有被回收.而这块value永远不会被访问到了. 所以存在着内存泄露. 最好 ...
- 多测师讲解selenium--常用关键字归纳-_高级讲师肖sir
常见的定位方式: 1.通过id定位 id=kw 2.通过name定位 name=wd 3.通过xpath相对路径定位:xpath=//*[@id="kw"] 4.通过两个属性值定位 ...
- day27 Pyhton 面向对象02 组合
# 组合 # 什么是组合 : 一个类对象的属性是另外一个类的对象 class Person: def __init__(self,name,sex,hp,mp,ad): self.name = nam ...
- 【线段树】BZOJ 5334 数学计算
题目内容 小豆现在有一个数\(x\),初始值为\(1\).小豆有\(Q\)次操作,操作有两种类型: 1 m:\(x=x×m\),输出\(x\ mod\ M\): 2 pos:\(x=x/\)第\(po ...
- VIM 批量注释的两种方法 (转)
方法一 ctrl+v 进入列编辑模式,向下或向上移动光标,把需要注释的行的开头标记起来,然后按大写的I(shift+i),再插入注释符,比如"//",再按Esc,就会全部注释了 批 ...
- centos8平台用ffprobe获取视频文件信息(ffmpeg4.2.2)
一,ffprobe的作用 ffprobe是强大的视频分析工具, 用于从多媒体流中获取相关信息或查看文件格式信息, 并以可读的方式打印 说明:刘宏缔的架构森林是一个专注架构的博客,地址:https:// ...
- Tomcat6.0 支持 https
环境信息 Linux系统 + Tomcat (程序页面可以运行前提下) 条件:安装了JDK 查看指定版本信息 1 进入$JAVA_HOME/bin目录 (一般是这个目录 /usr/java ...
- 通过两行代码即可调整苹果电脑 Launchpad 图标大小
之前用 13 寸 Mac 的时候我还没觉得,后来换了 16 寸就发现有点不对劲了.因为 Mac 的高分辨率,当你进入 Launchpad 界面,应用图标的大小可能会让你怀疑:这特么是苹果的设计吗?有点 ...