spring boot的单个文件多文件上传原理及使用
一、原理
自动配置原理
文件上传自动配置类-MultipartAutoConfiguration-MultipartProperties
- 自动配置好了 StandardServletMultipartResolver 【文件上传解析器】
- 原理步骤
- 1、请求进来使用文件上传解析器判断(isMultipart)并封装(resolveMultipart,返回MultipartHttpServletRequest)文件上传请求
- 2、参数解析器来解析请求中的文件内容封装成MultipartFile
- 3、将request中文件信息封装为一个Map;MultiValueMap<String, MultipartFile>
FileCopyUtils。实现文件流的拷贝
二、使用篇
表单
文件上传:form中一定要加 enctype="multipart/form-data"表示文件上传
多文件上传 一定要在input中加multiple
如:input type="file" id="exampleInputFile1" name="images" multiple> 表示多文件上传
<header class="panel-heading">文件上传</header><div class="panel-body"><form role="form" enctype="multipart/form-data" method="post" th:action="@{/multipart}"><div class="form-group"><label for="exampleInputEmail1">用户名</label><input type="email" class="form-control" name="username" id="exampleInputEmail1" placeholder="Enter email"></div><div class="form-group"><label for="exampleInputPassword1">密码</label><input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password"></div><div class="form-group"><label for="exampleInputFile">最喜欢的图片</label><input type="file" id="exampleInputFile" name="img"></div><div class="form-group"><label for="exampleInputFile1">最喜欢的图片</label><input type="file" id="exampleInputFile1" name="images" multiple></div><div class="checkbox"><label><input type="checkbox"> Check me out</label></div><button type="submit" class="btn btn-primary">Submit</button></form>
设置控制器进行文件上传
package com.example.controller;import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.UUID;/*** @author 谭铖* 文件上传*/
@Slf4j
@Controller
public class multipartFile {@GetMapping("/form_layouts")public String flot_chart(){return "MultipartFile/form_layouts";}@PostMapping("/multipart")public String multipart(@RequestParam(value = "username",required = false) String username,@RequestParam(value = "password",required = false) String password,@RequestPart("img") MultipartFile img,@RequestPart("images") MultipartFile [] images,HttpServletRequest request,HttpSession session) throws IOException {log.info("上传的信息:username={},password={} ,Img={},photos={}",username,password,img.getSize(),images.length);
// String path = request.getSession().getServletContext().getRealPath("/upload/");
// System.out.println(path);判断该路径是否存在
// File file = new File(path);
// // 若不存在则创建该文件夹
// if(!file.exists()){
// file.mkdirs();
// }if (!img.isEmpty()) {String originalFilename = img.getOriginalFilename();img.transferTo(new File("D:\\"+originalFilename));}if (images.length > 0) {for (MultipartFile mult:images) {String originalFilename1 = mult.getOriginalFilename();mult.transferTo(new File("D:\\"+originalFilename1));}}log.info(request.getRequestURI());return "index";}
}
即可实现文件上传因为springboot都是auto配置好的非常方便
当然如果你要设置你的文件大小配置可以修改application.properties文件
#单个文件最大限制
spring.servlet.multipart.max-file-size=100MB
#提交的全部文件最大限制
spring.servlet.multipart.max-request-size=100MB
为什么能修改呢我们看源码上传配置文件写了
然后看源码中配置好好多默认设置因为自动配置我就可以在配置文件中调用spring.servlet.multipart修改他的配置进行操作了
/** Copyright 2012-2019 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** https://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package org.springframework.boot.autoconfigure.web.servlet;import javax.servlet.MultipartConfigElement;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.util.unit.DataSize;/*** Properties to be used in configuring a {@link MultipartConfigElement}.* <ul>* <li>{@link #getLocation() location} specifies the directory where uploaded files will* be stored. When not specified, a temporary directory will be used.</li>* <li>{@link #getMaxFileSize() max-file-size} specifies the maximum size permitted for* uploaded files. The default is 1MB</li>* <li>{@link #getMaxRequestSize() max-request-size} specifies the maximum size allowed* for {@literal multipart/form-data} requests. The default is 10MB.</li>* <li>{@link #getFileSizeThreshold() file-size-threshold} specifies the size threshold* after which files will be written to disk. The default is 0.</li>* </ul>* <p>* These properties are ultimately passed to {@link MultipartConfigFactory} which means* you may specify numeric values using {@literal long} values or using more readable* {@link DataSize} variants.** @author Josh Long* @author Toshiaki Maki* @author Stephane Nicoll* @since 2.0.0*/
@ConfigurationProperties(prefix = "spring.servlet.multipart", ignoreUnknownFields = false)
public class MultipartProperties {/*** Whether to enable support of multipart uploads.*/private boolean enabled = true;/*** Intermediate location of uploaded files.*/private String location;/*** Max file size.*/private DataSize maxFileSize = DataSize.ofMegabytes(1);/*** Max request size.*/private DataSize maxRequestSize = DataSize.ofMegabytes(10);/*** Threshold after which files are written to disk.*/private DataSize fileSizeThreshold = DataSize.ofBytes(0);/*** Whether to resolve the multipart request lazily at the time of file or parameter* access.*/private boolean resolveLazily = false;public boolean getEnabled() {return this.enabled;}public void setEnabled(boolean enabled) {this.enabled = enabled;}public String getLocation() {return this.location;}public void setLocation(String location) {this.location = location;}public DataSize getMaxFileSize() {return this.maxFileSize;}public void setMaxFileSize(DataSize maxFileSize) {this.maxFileSize = maxFileSize;}public DataSize getMaxRequestSize() {return this.maxRequestSize;}public void setMaxRequestSize(DataSize maxRequestSize) {this.maxRequestSize = maxRequestSize;}public DataSize getFileSizeThreshold() {return this.fileSizeThreshold;}public void setFileSizeThreshold(DataSize fileSizeThreshold) {this.fileSizeThreshold = fileSizeThreshold;}public boolean isResolveLazily() {return this.resolveLazily;}public void setResolveLazily(boolean resolveLazily) {this.resolveLazily = resolveLazily;}/*** Create a new {@link MultipartConfigElement} using the properties.* @return a new {@link MultipartConfigElement} configured using there properties*/public MultipartConfigElement createMultipartConfig() {MultipartConfigFactory factory = new MultipartConfigFactory();PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();map.from(this.fileSizeThreshold).to(factory::setFileSizeThreshold);map.from(this.location).whenHasText().to(factory::setLocation);map.from(this.maxRequestSize).to(factory::setMaxRequestSize);map.from(this.maxFileSize).to(factory::setMaxFileSize);return factory.createMultipartConfig();}}
好了这样就实现了多文件上传
spring boot的单个文件多文件上传原理及使用相关推荐
- java批量上传文件_Spring boot 实现单个或批量文件上传功能
一:添加依赖: org.springframework.boot spring-boot-starter-thymeleaf javax.servlet jstl org.apache.tomcat. ...
- Spring Boot配置MinIO(实现文件上传、下载、删除)
1 MinIO MinIO 是一个基于Apache License v2.0开源协议的对象存储服务.它兼容亚马逊S3云存储服务接口,非常适合于存储大容量非结构化的数据,例如图片.视频.日志文件.备份数 ...
- spring boot读取resources下面的文件图片
spring boot读取resources下面的文件图片 下面的代码是为了保证在打成jar包的情况下依然能够有效读取到文件. 先看项目目录结构: 我是想读取resources下面的图片,下面放上代码 ...
- spring boot结合FastDFSClient做下载文件注意事项
spring boot结合FastDFSClient做下载文件注意事项 1.后台下载方法走完后,前端页面浏览器一直没出现下载框. 2.ie浏览器兼容问题. 下面的FastDFSClient类依赖fdf ...
- java配置文件放置到jar外_java相关:Spring Boot 把配置文件和日志文件放到jar外部...
java相关:Spring Boot 把配置文件和日志文件放到jar外部 发布于 2020-3-6| 复制链接 如果不想使用默认的application.properties,而想将属性文件放到jar ...
- Spring Boot 推荐的基础 POM 文件
Spring Boot 推荐的基础 POM 文件 名称 说明 spring-boot-starter 核心 POM,包含自动配置支持.日志库和对 YAML 配置文件的支持. spring-boot-s ...
- 单个文件过大上传服务器的方案,上传很大的文件到云服务器上
上传很大的文件到云服务器上 内容精选 换一换 安装传输工具在本地主机和Windows云服务器上分别安装数据传输工具,将文件上传到云服务器.例如QQ.exe.在本地主机和Windows云服务器上分别安装 ...
- 补习系列(11)-springboot 文件上传原理
一.文件上传原理 一个文件上传的过程如下图所示: 浏览器发起HTTP POST请求,指定请求头: Content-Type: multipart/form-data 服务端解析请求内容,执行文件保存处 ...
- php webuploader大文件,web uploader 上传大文件总结
由于业务需要,需要上传大文件,已有的版本无法处理IE版本,经过调研,百度的 webuploader 支持 IE 浏览器,而且支持计算MD5值,进而可以实现秒传的功能. 大文件上传主要分为三部分,预上传 ...
- SpringBoot+El-upload实现上传文件到通用上传接口并返回文件全路径(若依前后端分离版源码分析)
场景 SpringBoot+ElementUI实现通用文件下载请求(全流程图文详细教程): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...
最新文章
- 红帽启动apache服务器_CentOS6.5环境下搭建Apache httpd服务器
- textview是否超过一行_如何实现一个TextView自动换行单词不会被拆分
- 输出apk_KT被横扫吞下五连败果 APK拿下首胜 小夫笑得十分开心
- sap 一代增强_SAP增强Enhancement
- 【MM模块】Procurement for Consumption Material 消耗性物料的采购流程
- 什么是Linux系统调用system call?(Linux内核中设置的一组用于实现各种系统功能的子程序)(区别于标准C库函数调用)核心态和用户态的概念、中断的概念、系统调用号、系统调用表
- 译 | Azure 应用服务中的程序崩溃监控
- 注解实现json序列化的时候自动进行数据脱敏
- MyBatis 源码自我解读
- java .class 实例对象_通过Class类获取对象(实例讲解)
- 【图像融合】图像融合质量评价方法的研究
- java中通过反射得到StatusBarManager
- 相机模型与标定(六)--单应性求解
- 非常好的截图软件:FSCapture,非常非常非常推荐(百度云链接)
- 机器学习及深度学习技术在海洋科学方面的应用
- 《Robust Consistent Video Depth Estimation》论文笔记
- 算法之狄克斯特拉算法
- C#开发微信门户及应用(46)-基于Bootstrap的微信门户应用管理系统功能介绍
- Kali之Crunch:自定义字典
- 关于STM32 Hal 库函数编写的程序 在编译时报错 :“Error: L6218E: Undefined symbol 函数名 (referred from xx.o)” 的解决办法