您的位置:首页 > 编程语言 > Java开发

JAVA开发Spring MVC实现文件上传

2019-06-05 11:03 316 查看

在spring mvc中实现文件上传的大致步骤如下:
一,pox.xml配置中添加依赖,

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

二,在resources中配置新建spring-mvc.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!--suppress SpringXmlModelInspection -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--suppress SpringXmlModelInspection -->
<!--开启注解-->
<context:component-scan base-package="com.k9501.controller"/>
<!--开启适配器和处理器的注解-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀和后缀-->
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

<!--文件上传配置-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置字符集-->
<property name="defaultEncoding" value="UTF-8"/>
<!--设置文件上传大小-->
<property name="maxUploadSizePerFile" value="5242880"/>
<!--设置总大小-->
<property name="maxUploadSize" value="47185920"/>
</bean>
</beans>

三,页面jsp
在webapp文件夹下,新建upload.jsp文件

<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/6/4
Time: 15:43
To change this template use File | Settings | File Templates
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>
<title>文件上传</title>
</head>
<body>
单个文件上传
<form action="${pageContext.request.contextPath}/upload.action" method="post" enctype="multipart/form-data">
头像:<input type="file" name="imgName"> <input type="submit">

</form>
<hr/>
多文件上传
<form action="${pageContext.request.contextPath}/uploadMany.action" method="post" enctype="multipart/form-data">
头像:<input type="file" multiple="multiple" name="fileMany"> <input type="submit">

</form>
<hr/>
多文件上传,分包处理
<form action="${pageContext.request.contextPath}/uploadManyPage.action" method="post" enctype="multipart/form-data">
头像:<input type="file" multiple="multiple" name="fileManyPage"> <input type="submit">

</form>
<hr/>
多文件上传,分包处理工具类
<form action="${pageContext.request.contextPath}/uploadManyPageUtil.action" method="post" enctype="multipart/form-data">
头像:<input type="file" multiple="multiple" name="fileName"> <input type="submit">

</form>
</body>
</html>

四,写控制器
(导包省略)

@Controller
public class UploadController {
//上传单个文件
@RequestMapping(value = "/upload.action",produces = "application/json;charset=utf-8")
@ResponseBody
public String upload(MultipartFile imgName){
String originalFilename = imgName.getOriginalFilename();

try {
imgName.transferTo(new File("E:\\study\\images",originalFilename));
return "success";
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}

//多文件
@RequestMapping(value = "/uploadMany.action",produces = "application/json;charset=utf-8")
@ResponseBody
public String uploadMany(MultipartRequest request){
List<MultipartFile> multipartFileList = request.getFiles("fileMany");
try {
for (int i=0;multipartFileList!=null&&i<multipartFileList.size();i++) {

MultipartFile multipartFile = multipartFileList.get(i);

String originalFilename = multipartFile.getOriginalFilename();

multipartFile.transferTo(new File("E:\\study\\images", originalFilename));
}
return "success";

} catch (IOException e) {
e.printStackTrace();
return "error";
}
}

//多包处理,
@RequestMapping(value = "/uploadManyPage.action",produces = "application/json;charset=utf-8")
@ResponseBody
public String uploadManyPage(MultipartRequest request){
// 路径如  e:/images/2019/06/04/16/51/35/UUID.jpg
List<MultipartFile> multipartFileList = request.getFiles("fileManyPage");
try {
for (int i=0;multipartFileList!=null&&i<multipartFileList.size();i++) {
MultipartFile multipartFile = multipartFileList.get(i);
//获取图片名称
String originalFilename = multipartFile.getOriginalFilename();
//获取文件类型、
String lastPath = originalFilename.substring(originalFilename.lastIndexOf("."));
//uuid
String uuidPath = UUID.randomUUID().toString();
//获取日期包
String datePath = new SimpleDateFormat("yyyy\\MM\\dd\\HH\\mm\\ss").format(new Date());
//完成路径
File file = new File("e:\\study\\images", datePath);
//判断文件夹是否存在
if (!file.exists()){
file.mkdirs();
}
String endPath="E:\\study\\images\\"+datePath+"\\"+uuidPath+lastPath;
System.out.println("endPath = " + endPath);
multipartFile.transferTo(new File(endPath));
}
return "success";
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}

//多包处理, 工具类
@RequestMapping(value = "/uploadManyPageUtil.action",produces = "application/json;charset=utf-8")
@ResponseBody
public String uploadManyPageUtil(MultipartRequest request){
FileUploadUtil.fileUploadUtil(request,"fileName","e:\\study\\images\\");

return "success";
}
}

另外多包处理util工具类参考:

public class FileUploadUtil {
public static Map<String,Object> fileUploadUtil(MultipartRequest request,String fileName,String targetPage){
// 路径如  e:/images/2019/06/04/16/51/35/UUID.jpg
List<MultipartFile> multipartFileList = request.getFiles("fileName");
try {
for (int i=0;multipartFileList!=null&&i<multipartFileList.size();i++) {
MultipartFile multipartFile = multipartFileList.get(i);
//获取图片名称
String originalFilename = multipartFile.getOriginalFilename();
//获取文件类型、
String lastPath = originalFilename.substring(originalFilename.lastIndexOf("."));
//uuid
String uuidPath = UUID.randomUUID().toString();
//获取日期包
String datePath = new SimpleDateFormat("yyyy\\MM\\dd\\HH\\mm\\ss").format(new Date());
//完成路径
File file = new File(targetPage, datePath);
//判断文件夹是否存在
if (!file.exists()){
file.mkdirs();
}
String endPath=targetPage+datePath+"\\"+uuidPath+lastPath;

multipartFile.transferTo(new File(endPath));
}
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: