一、原理

自动配置原理

文件上传自动配置类-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的单个文件多文件上传原理及使用相关推荐

  1. java批量上传文件_Spring boot 实现单个或批量文件上传功能

    一:添加依赖: org.springframework.boot spring-boot-starter-thymeleaf javax.servlet jstl org.apache.tomcat. ...

  2. Spring Boot配置MinIO(实现文件上传、下载、删除)

    1 MinIO MinIO 是一个基于Apache License v2.0开源协议的对象存储服务.它兼容亚马逊S3云存储服务接口,非常适合于存储大容量非结构化的数据,例如图片.视频.日志文件.备份数 ...

  3. spring boot读取resources下面的文件图片

    spring boot读取resources下面的文件图片 下面的代码是为了保证在打成jar包的情况下依然能够有效读取到文件. 先看项目目录结构: 我是想读取resources下面的图片,下面放上代码 ...

  4. spring boot结合FastDFSClient做下载文件注意事项

    spring boot结合FastDFSClient做下载文件注意事项 1.后台下载方法走完后,前端页面浏览器一直没出现下载框. 2.ie浏览器兼容问题. 下面的FastDFSClient类依赖fdf ...

  5. java配置文件放置到jar外_java相关:Spring Boot 把配置文件和日志文件放到jar外部...

    java相关:Spring Boot 把配置文件和日志文件放到jar外部 发布于 2020-3-6| 复制链接 如果不想使用默认的application.properties,而想将属性文件放到jar ...

  6. Spring Boot 推荐的基础 POM 文件

    Spring Boot 推荐的基础 POM 文件 名称 说明 spring-boot-starter 核心 POM,包含自动配置支持.日志库和对 YAML 配置文件的支持. spring-boot-s ...

  7. 单个文件过大上传服务器的方案,上传很大的文件到云服务器上

    上传很大的文件到云服务器上 内容精选 换一换 安装传输工具在本地主机和Windows云服务器上分别安装数据传输工具,将文件上传到云服务器.例如QQ.exe.在本地主机和Windows云服务器上分别安装 ...

  8. 补习系列(11)-springboot 文件上传原理

    一.文件上传原理 一个文件上传的过程如下图所示: 浏览器发起HTTP POST请求,指定请求头: Content-Type: multipart/form-data 服务端解析请求内容,执行文件保存处 ...

  9. php webuploader大文件,web uploader 上传大文件总结

    由于业务需要,需要上传大文件,已有的版本无法处理IE版本,经过调研,百度的 webuploader 支持 IE 浏览器,而且支持计算MD5值,进而可以实现秒传的功能. 大文件上传主要分为三部分,预上传 ...

  10. SpringBoot+El-upload实现上传文件到通用上传接口并返回文件全路径(若依前后端分离版源码分析)

    场景 SpringBoot+ElementUI实现通用文件下载请求(全流程图文详细教程): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...

最新文章

  1. 感知机搞不定逻辑XOR?Science新研究表示人脑单个神经元就能做到
  2. juniper M320路由器基本配置
  3. python推荐入门书籍-学python入门看什么书
  4. winFrom简单引用Webservice
  5. Norse Attack Map网络攻击实时监测地图
  6. 计算机网断IP修改,修改计算机名、IP
  7. 自定义路由匹配和生成
  8. windows设置mysql使用率_Windows下配置Mysql
  9. python logger设置信息取得_shell 脚本中如何获取 python logging 打印的信息?
  10. ArcGIS 的 http://localhost:8399/arcgis/rest/services 无法打开,显示404 的解决办法
  11. (转)Openlayers 2.X加载高德地图
  12. 根据线程名获取线程及停止线程
  13. OpenCV问题集锦,图片显示不出来,WaitKey(0),imread()不能读图片,未经处理的异常,等问题集合
  14. Oracle数据库用户查询常用命令
  15. opencv的sift算法
  16. 计算机电源如何选配,自己组装电脑时,该怎么选择电源才合适?
  17. cdr 表格自动填充文字_cdr中看似简单的小工具,你真的会用吗?
  18. C++ 遇到reference to ' *** ' is ambiguous 错误
  19. 软件测试中的心理学效应
  20. 三菱PLC FX3GA系列 FNC57 PLSY 脉冲输出

热门文章

  1. 使用Fluorine的一些心得
  2. 服务器上的垃圾器文件恢复,文件误删不要怕,帮你找回Win10回收站清空文件
  3. Ubuntu USB转RJ-45 驱动安装insmod asix.ko error,Recovering journal
  4. ubuntu使用教程与常用命令
  5. 基于架空线路警示器跌落报警,架空线路故障指示器跌落报警NB实现
  6. Berkeley DB学习(一)
  7. 北京理工大学复试上机题汇总
  8. php生成密码及密码检验
  9. 企业ERP运维技巧(实操干货)
  10. 放大器:A、B、AB、D、G、H