【Spring】SpringMVC之上传文件
这里笔者介绍利用SpringMVC上传图片的操作。
步骤
1. 引入jar文件
不仅需要导入开发SpringMVC相关的包,还需要导入 commons-fileupload-1.2.1.jar 和 commons-io-1.3.2.jar 包
2. 配置applicationContext.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
3. 编写html文件:
需要注意: 提交文件, 只能使用POST方式, 并且要指定enctype="multipart/form-data"
例如:
<form action="file.do" method="POST" enctype="multipart/form-data"> 请选择您要上传的文件:<br><br> <input type="file" name="file"/><br> <input type="submit"/> </form>
4. 编写接收上传文件的Controller了 ,接收的文件的类型: MultipartFile
例如:
@RequestMapping("/file.do") public String fileUpload(MultipartFile file){ //上传的文件: file System.out.println("上传的文件名称为:"+file.getOriginalFilename()); return "result"; }
Demo
下面是一个接受上传图片的Demo,该Demo能够把用户上传的图片存储到部署项目的根目录下面。那么如何查看自己项目的根目录:点击 项目->.metadata->.plugins->org.eclipse.wst.server.core->tmp0->wtpwebapps ,在里面就可以看到部署的项目了。
jsp文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ 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> 文件上传成功:${imagePath } </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ 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> 文件过大, 请上传1M以内的图片 </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ 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>上传错误</title> </head> <body> 请上传图片类型~ .jpg .png .jpeg </body> </html>
文件上传表单:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ 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>文件上传</title> </head> <body> <form action="fileupload.do" method="POST" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="提交"/> </form> </body> </html>
dispatcherServlet-servlet.xml文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 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-4.3.xsd"> <!--指定注解扫描包--> <context:component-scan base-package="cn"></context:component-scan> <!--开启注解扫描--> <mvc:annotation-driven/> <!--配置视图--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"> <value>org.springframework.web.servlet.view.InternalResourceView</value> </property> <!--jsp存放的目录--> <property name="prefix"> <value></value> </property> <!--jsp文件的后缀--> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean> </beans>
web.xml文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>SpringMVC_FileUpLoad</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
FileController.java控制器文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package cn.xdl.Controller; import java.io.File; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; @Controller public class FileController { @RequestMapping("/fileupload.do") public String fileUpload(MultipartFile file,HttpServletResponse response,HttpServletRequest request){ //判断文件的类型------------------// String fileName = file.getOriginalFilename(); if(fileName.endsWith(".jpeg")||fileName.endsWith(".png")||fileName.endsWith(".jpg")){ //判断文件的类型------------------// //上传的是图片 //图片大小的判断---------------------// System.out.println("上传的图片的大小为: "+ file.getSize()); int size = 1024*1024; //文件大小是否过大 , true表示过大 boolean flag = false; if(file.getSize()<Integer.MAX_VALUE){ int fileSize = (int) file.getSize(); if(fileSize>size){ //文件过大 flag = true; }else{ //大小合适 flag = false; } }else{ //文件大小过大 flag = true; } //文件过大 则响应错误页面 if(flag){ //文件过大 return "redirect:fileUploadError.jsp"; }else{ //文件大小正常 ,将文件存储到项目当前运行目录下 String dirPath = request.getServletContext().getRealPath("/");//获取当前项目运行时的目录 // 获取到的目录: webContent目录 System.out.println(dirPath); File imgDir = new File(dirPath+"/images"); if(!imgDir.exists()) imgDir.mkdirs(); try { fileName = fileName.replace(".", ","); String newFileName = System.currentTimeMillis()+"."+(fileName.split(",")[fileName.split(",").length-1]); file.transferTo(new File(imgDir,newFileName )); request.getSession().setAttribute("imagePath", "<a href='images/"+newFileName+"'>点击查看</a>"); return "redirect:fileUploadOk.jsp"; } catch (Exception e) { e.printStackTrace(); } } }else{ //上传的是其他文件 System.out.println("上传的不是图片"); } return "error"; } }