SpringMVC多文件上传

本文介绍如何在Spring MVC框架中实现多文件上传功能。主要步骤包括:在配置文件中添加多文件支持、引入必要的jar包、设置表单属性及提交方式、编写控制器处理文件保存等。

一、方法步骤

1.在Spring-mvc.xml配置文件中添加多文件支持

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<property name="defaultEncoding" value="UTF-8"/>  
   <property name="maxUploadSize" value="10000000"/>


</bean>


2.必要的包

commons.fileupload.jar

commons.io.jar


3.页面

form加上属性enctype="multipart/form-data"

input加上multiple="multiple",如果不加只能选择单个文件


二、代码     

1.jsp页面代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/file/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple="multiple"/>
<input type="submit" value="上传文件"/>
</form>
</body>
</html>


2.spring-mvc.xml添加

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<property name="defaultEncoding" value="UTF-8"/>  
   <property name="maxUploadSize" value="10000000"/>


</bean>


3.controller中

@RequestMapping("/upload")
public String upload(@RequestParam(value="file",required=false) MultipartFile[] files, 
HttpServletRequest request)throws Exception{
String path = "E:/project/crm/upload";
logger.info("----------"+path);
for(MultipartFile file:files){
String fileName = file.getOriginalFilename();
File targetFile = new File(path, fileName);
file.transferTo(targetFile);
}
return "page/upload";
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值