SpringMVC 文件上传(单、多文件)
2018-08-04 本文已影响24人
tingshuo123
工程结构
image.png依赖jar包
需要3个文件上传的jar包
image.png
SpringMVC 配置文件
要用SpringMVC实现文件上传功能,需要在SpringMVC配置文件中添加文件上传组件。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
<!-- spring包扫描功能 -->
<context:component-scan base-package="com.project.action"/>
<!-- 配置注解映射处理器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<!-- 配置注解处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
<!-- 注册springmvc的文件上传组件 文件解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>52428800</value>
</property>
</bean>
</beans>
前端视图
相比于普通表单,需要添加 enctype=multipart/form-data
属性
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SpringMVC 文件上传</title>
</head>
<body>
<form action="/SpringMVC_Upload2/upload.action" method="post"
enctype=multipart/form-data>
<input type="file" name="file01" /><br />
<input type="file" name="file02" /><br />
<input type="file" name="file03" /><br />
<button type="submit">上传</button>
</form>
</body>
</html>
Controller
想要实现文件上传需要用到 HttpServletReqeust
对象
package com.project.action;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.project.util.FileUploadUtil;
@Controller
public class UploadAction {
@RequestMapping("/upload.action")
public void saveFile(HttpServletRequest req) {
System.out.println("请求到 acton ");
// 保存文件
List<String> filesname = FileUploadUtil.saveFiles(req);
System.out.println(filesname);
}
}
文件上传工具类
package com.project.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
public class FileUploadUtil {
/**
* 保存多个文件
* @param req
* @return 文件名的Set集合
*/
public static List<String> saveFiles(HttpServletRequest req) {
List<String> fileNameSet = new ArrayList<String>();
CommonsMultipartResolver multipartReslver = new CommonsMultipartResolver(req.getSession().getServletContext());
// 检查 form 是否有 enctype="multipart/form-data" 属性值
if (multipartReslver.isMultipart(req)) {
// request 转换为 多部分 request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) req;
// 获取 multiRequest 中所有文件名
Iterator<String> iter = multiRequest.getFileNames();
// 遍历所有文件
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile(iter.next().toString());
// 检查文件是否存在,及文件是否为空
if (file != null && !file.isEmpty()) {
// 保存文件
String filename = saveFile(req, file);
fileNameSet.add(filename);
}
}
}
return fileNameSet;
}
/**
* 保存单个文件,保存成功返回文件名,否则返回null
*
* @param req
* @param file
* @return 保存文件的名字
*/
public static String saveFile(HttpServletRequest req, MultipartFile file) {
String result = null;
// 获取原始文件名
String fileName = file.getOriginalFilename();
// 给文件设置新名字
String newFileName = UUID.randomUUID() + "_" + fileName;
// 需要保存的文件路径
ServletContext context = req.getServletContext();
String path = context.getRealPath("/upload");
// 检查目录是否存在
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
// 在目录下创建文件
File newFile = new File(path, newFileName);
// 将上传的文件数据,写入到file对象
try {
file.transferTo(newFile);
result = newFileName;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return newFileName;
}
}