Springmvc为文件上传提供了直接的支持,这种支持是即插即用的MultipartResolver实现的。Springmvc使用了Apache Commons FileUpload技术实现了Multipart Resoler实现类:CommonsMultipartResoler.
步骤如下:
- pom中引入依赖包
<!-- 文件上传依赖包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
-
在Springmvc 配置文件中配置MultipartResolver类
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSizePerFile" value="#{10*1024*1024}" /><!--单个文件大小限制(byte) --> <property name="maxUploadSize" value="#{100*1024*1024}" /><!-- 整个请求大小限制(byte) --> <property name="defaultEncoding" value="utf-8"></property> </bean>
-
案列:
前端
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); request.setAttribute("path", path); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>uploadpage</title> </head> <body> <h3>单文件上传</h3> <form method="post" action="${path}/upload/upload1.do" enctype="multipart/form-data"> 文件:<input type="file" name="file1"><br/> <input type="submit" value="提交"> </form> <br> <br> <h3>多文件上传</h3> <form method="post" action="${path}/upload/upload2.do" enctype="multipart/form-data"> 文件1:<input type="file" name="file1"><br/> 文件2:<input type="file" name="file2"><br/> <input type="submit" value="提交"> </form> <br> <br> <h3>通过 MultipartHttpServletRequest 处理文件上传</h3> <form method="post" action="${path}/upload/upload3.do" enctype="multipart/form-data"> 姓名:<input name="name" value="路人"/> <br/> 年龄:<input name="age" value="30"/><br/> 文件1:<input type="file" name="file1"><br/> 文件2:<input type="file" name="file2"><br/> 多张身份证图片<br/> <input name="idCardImg" type="file"/><br/> <input name="idCardImg" type="file"/><br/> <input type="submit" value="提交"> </form> <br> <br> <h3>自定义对象接收多文件上传</h3> <form method="post" action="${path}/upload/upload4.do" enctype="multipart/form-data"> 姓名:<input name="name" value="路人"/> <br/> 年龄:<input name="age" value="30"/><br/> 头像图片:<input name="headImg" type="file"/><br/> 多张身份证图片<br/> <input name="idCardImg" type="file"/><br/> <input name="idCardImg" type="file"/><br/> <input type="submit" value="提交"> </form> <h3>文件上传</h3> <form method="post" action="${path}/upload/upload5.do" enctype="multipart/form-data"> 文件1:<input type="file" name="file"><br/> <input type="submit" value="提交"> </form> </body> </html>
后端:
封装一个类用来接更简便的接收图片 public class UserDto { //姓名 private String name; //年龄 private Integer age; //头像 private MultipartFile headImg; //身份证(多张图像? private List idCardImg; setter....... }
/**
Description:文件上传
@author ljd
@date 2022年8月17日 上午10:06:24
*/
package com.restfullDemo.controller;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.restfullDemo.model.User;
import com.restfullDemo.model.UserDto;
@Controller
@RequestMapping("upload")
public class UploadFileDemo {
private ServletContext context;
private String path;
@RequestMapping
public String uploadpage() {
return "uploadpage";
}
/**
* 将通用的参数及属性用@ModelAttribute标签来注入,简化代码
*
* @param session
* @param response
*/
@ModelAttribute
private void testModelAttribute(HttpSession session, HttpServletResponse response) {
/* 设置编码 ,同时需要在web.xml中配置相关过滤器 */
response.setContentType("text/html;charset=utf8");
response.setCharacterEncoding("utf8");
context = session.getServletContext();
// 注getRealPath获取的路径,不管传参的尾部是否有带"/",在路径拼接时,最好带上File.separator来加上反斜杠,因为有的容器不识别传参时的"/"
path = context.getRealPath("/upload") + File.separator;
System.out.println(path);
}
/**
* 单文件上传 1、MultipartFile用来接收表单中上传的文件 2、每个MultipartFile对应表单中的一个元素
* 3、@RequestParam("f1")用来自动接受表单中的哪个元素?value用来指定表单元素的名称
*
* @param f1
* @return
* @throws IOException
*/
@RequestMapping("upload1.do")
public ModelAndView upload1(@RequestParam("file1") MultipartFile f1) throws IOException {
// 获取文件名称
String originalFilename = f1.getOriginalFilename();
// String destFilePath = String.format("E:\\idea\\springmvc-series\\chat04-uploadfile\\src\\main\\webapp\\upfile\\%s", originalFilename);
// System.out.println("destFilePath:"+destFilePath);
File destFile = new File(path + originalFilename);
// 调用transferTo将上传的文件保存到指定的地址
f1.transferTo(destFile);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("uploadpage");
// modelAndView.addObject("msg", destFile.getAbsolutePath());
return modelAndView;
}
/**
* 多文件上传 1、方法中指定多个MultipartFile,每个MultipartFile对应一个上传的文件
* 2、@RequestParam("file1") 用来指定具体接受上传的表单中哪个元素的名称
*
* @param f1
* @param f2
* @return
* @throws IOException
* @throws IllegalStateException
*/
@RequestMapping("/upload2.do")
public ModelAndView upload2(@RequestParam("file1") MultipartFile f1, @RequestParam("file2") MultipartFile f2)
throws IOException {
System.out.println("f1:" + f1);
System.out.println("f2:" + f2);
String originalFilename1 = f1.getOriginalFilename();
String originalFilename2 = f2.getOriginalFilename();
System.out.println(path + originalFilename1);
File destFile1 = new File(path + originalFilename1);
File destFile2 = new File(path + originalFilename2);
f1.transferTo(destFile1);
f2.transferTo(destFile2);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("uploadpage");
modelAndView.addObject("msg", null);
return modelAndView;
}
/**
* 使用MultipartHttpServletRequest处理多文件上传
* 上传文件的http请求会被转换为MultipartHttpServletRequest类型
* MultipartHttpServletRequest中提供了很多很多方法用来获取请求中的参数 控制器中使用
* MultipartHttpServletRequest 来获取所有参数信息,分了 2 部分获取
*
* 1、先使用 request.getParameterMap()获取非文件类型的参数,即可以获取表单中的 name 和 age 这 2 个参数的信息
*
* 2、通过 request.getMultiFileMap()获取文件类型的参数,即可以获取表单中 file1 和 file2 这 2 个文件的信息
*
* @param request
* @param u 为了简便,封装了一个user对像接收参数
* @return
*/
@RequestMapping("/upload3.do")
public ModelAndView upload3(MultipartHttpServletRequest request, User u) {
// 1.获取表单中非文件数据
System.out.println("---------获取表单中非文件数据---------");
Map parameterMap = request.getParameterMap();
parameterMap.forEach((name, values) -> {
System.out.println(String.format("%s:%s", name, Arrays.asList(values)));
});
System.out.println(u);
// 2、获取表单中文件数据
System.out.println("---------获取表单中文件数据---------");
MultiValueMap multiFileMap = request.getMultiFileMap();
// 2、遍历表单中元素信息
multiFileMap.forEach((name, files) -> {
System.out.println(String.format("%s:%s", name, files));
});
// 单个文件获取方法
MultipartFile file = request.getFile("file1");
System.out.println("单个文件名:" + file.getOriginalFilename());
// 多个文件获取方法
List files = request.getFiles("idCardImg");
System.out.println("files size:" + files.size());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("uploadpage");
modelAndView.addObject("msg", "上传成功");
return modelAndView;
}
/**
* 这个表单用来输入用户信息:
*
* 姓名、年龄、头像图片、2 张身份证图片
*
* @param userDto 封装了一个对象,用于收对象对应的参数
* @return
*/
@RequestMapping("/upload4.do")
public ModelAndView upload4(UserDto userDto) {
System.out.println("姓名:" + userDto.getName());
System.out.println("年龄:" + userDto.getAge());
System.out.println("头像文件:" + userDto.getHeadImg());
System.out.println("多张身份证文件:" + Arrays.asList(userDto.getIdCardImg()));
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("uploadpage");
modelAndView.addObject("msg", "上传成功");
return modelAndView;
}
@RequestMapping("/upload5.do")
public String uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
/* 判断上传的文件是否为空 */
if (!file.isEmpty()) {
/* 文件不为空时,则获取文件存放路径 */
String path = request.getServletContext().getRealPath("upload");
/* 获取文件名称 */
String fileName = file.getOriginalFilename();
File filePath = new File(path, fileName);
/* 判断文件夹是否存在,不存则创建 */
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
/* 将上传的文件保存到指定位置 */
file.transferTo(filePath);
return "success";
}
return "error";
}
}
MultipartFile常用方法
//getName() 返回参数的名称
String getName();
//获取源文件的昵称
@Nullable
String getOriginalFilename();
//getContentType() 返回文件的内容类型
@Nullable
String getContentType();
//isEmpty() 判断是否为空,或者上传的文件是否有内容
boolean isEmpty();
//getSize() 返回文件大小 以字节为单位
long getSize();
//getBytes() 将文件内容转化成一个byte[] 返回
byte[] getBytes() throws IOException;
//getInputStream() 返回InputStream读取文件的内容
InputStream getInputStream() throws IOException;
default Resource getResource() {
return new MultipartFileResource(this);
}
//transferTo(File dest) 用来把 MultipartFile 转换换成 File
void transferTo(File var1) throws IOException, IllegalStateException;
default void transferTo(Path dest) throws IOException, IllegalStateException {
FileCopyUtils.copy(this.getInputStream(), Files.newOutputStream(dest));
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/71215.html