Spring MVC上传文件

Spring MVC上传文件

1.Web.xml中添加:

    <servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<max-file-size>5242880</max-file-size> <!--上传单个文件的最大限制5MB -->
<max-request-size>20971520</max-request-size> <!--请求的最大限制20MB,上传多个文件总共大小 -->
<file-size-threshold>0</file-size-threshold> <!--当文件的大小超过临界值时将写入磁盘 -->
</multipart-config>
</servlet>
<!--拦截所有请求 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

2.Spring MVC配置文件中添加:

    <!-- 视图解析器 -->
<bean id="internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean> <bean id="multipartResolver"
class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
</bean>

3. 添加一个控制器

@Controller
@RequestMapping("/fileupload")
public class FileUploadController { @RequestMapping("page")
public String file(Model model){
return "fileupload";
} @RequestMapping(value="/saveFile",method=RequestMethod.POST)
public String saveFile(Model model,MultipartFile[] files,HttpServletRequest request) throws Exception{ //文件存放的位置
String path=request.getSession().getServletContext().getRealPath("/files");
System.out.println(path);
String ret="";
for (MultipartFile file : files) {
//保存文件
File tempFile=new File(path, file.getOriginalFilename());
file.transferTo(tempFile);
ret+="<img src='../files/"+file.getOriginalFilename()+"' width='300' />";
}
model.addAttribute("images", ret);
return "fileupload";
}
}

4.文件上传页面 fileupload.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>fileupload</title>
</head>
<body>
<h2>fileupload</h2>
<form action="saveFile" method="post" enctype="multipart/form-data">
<p>
<label for="files">文件:</label>
<input type="file" name="files" id="files" multiple="multiple" />
</p>
<p>
<button>提交</button>
</p>
<p>${images}</p>
</form>
</body>
</html>

5.浏览器访问

Spring MVC上传文件

end

上一篇:SpringMVC+jquery.uploadify 上传文件


下一篇:Spring MVC 上传文件