知识点:
- SpringMvc单文件上传
- SpringMvc多文件上传
这里我直接演示多文件上传,单文件的上传就不说了,不过代码都是现成的。
效果预览:
DEMO图:
添加文件上传jar包:
Web.xml配置文件:添加spring Servlet
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Spring-mvc.xml代码:
<?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:p="http://www.springframework.org/schema/p"
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/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 使用注解的包,包括子集 -->
<context:component-scan base-package="com"/>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="10000000"/>
</bean>
</beans>
FileUploadController
@Controller
public class FileUploadController {
//单文件上传
@RequestMapping("/upload")
public String uploadFile(@RequestParam("file1") MultipartFile file1,HttpServletRequest request)throws Exception{
String filePath=request.getServletContext().getRealPath("/");
System.out.println(filePath);
file1.transferTo(new File(filePath+"upload/"+file1.getOriginalFilename()));//上传到目录下的upload文件夹下。
return "redirect:success.jsp";
}
//多文件上传
@RequestMapping("/upload2")
public String uploadFiles(@RequestParam("file") MultipartFile[] files,HttpServletRequest request)throws Exception{
String filePath=request.getServletContext().getRealPath("/");
System.out.println(filePath);
for(MultipartFile file:files){
file.transferTo(new File(filePath+"upload/"+file.getOriginalFilename()));
}
return "redirect:success.jsp";
}
}
index.jsp:
<body>
<form action="upload2.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<th colspan="2">上传文件</th>
</tr>
<tr>
<td>文件一</td>
<td>
<input type="file" name="file"/>
</td>
</tr>
<tr>
<td>文件二</td>
<td>
<input type="file" name="file"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="上传文件"/>
</td>
</tr>
</table>
</form>
</body>
success.jsp:
<body>
上传成功
</body>
测试地址:http://localhost:8080/SpringMvc04/
查看你上传的文件的时候不是在项目下查看upload文件夹里面的是否有文件,而是在部署服务器下查看项目下的upload文件下,如我是查看的tomcat的地址:TomcatwebappsSpringMvc04upload。
好记性不如烂笔头,菜鸟边学边把学到的东西记录下来。