第一次写博客,写得不好,不吝赐教
springmvc将上传的文件封装在一个org.springframework.web.multipart.MultipartFile对象中,接口MultipartFile
具有以下几个方法:
- byte[] getBytes():以字节数组返回文件的内容;
- String getContentType():返回文件的内容类型;
- InputStream getInputStream():返回一个字节流,从中读取文件的内容;
- String getName():返回参数的名称;
- String getOriginalFilename():返回上传的文件名;
- long getSize():以字节为单位,返回文件的大小;
- boolean isEmpty():判断上传文件是否为空;
- void transfetTo(File destination):将上传文件保存在目标目录下。
下面贴出代码,以供参考:
web.xml配置文件代码:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>springmvc</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
springmvc配置文件的代码:
<?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:context = "http://www.springframework.org/schema/context" xmlns:aop = "http://www.springframework.org/schema/aop" xmlns:tx = "http://www.springframework.org/schema/tx" xmlns:mvc = "http://www.springframework.org/schema/mvc" xmlns:jee = "http://www.springframework.org/schema/jee" xmlns:jdbc = "http://www.springframework.org/schema/jdbc" xsi:schemaLocation = " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd"> <description>springMVC视图解析器</description> <context:component-scan base-package="com.yonyou"/> <!-- 开启注解 --> <mvc:default-servlet-handler/> <mvc:annotation-driven /> <!-- 处理静态资源 --> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <mvc:resources location="/*.jsp" mapping="/"/> <mvc:resources location="/*.html" mapping="/"/> <!-- 创建视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 配置multipartResolver bean --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 没有此属性表示没有最大文件容量限制 --> <property name="maxUploadSize" value="1000000000"/> <!-- 默认编码方式 --> <property name="defaultEncoding" value="UTF-8"/> <!-- 缓存大小 --> <property name="maxInMemorySize" value="40960"/> </bean> </beans>
上传控制器的代码(UploadController):
package com.yonyou.controller; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Scope("prototype") @Controller @RequestMapping("/files") public class UploadController { @RequestMapping(value="/input",method=RequestMethod.GET) public String inputFile(){ return "file/upload"; } @RequestMapping(value="/upload",method=RequestMethod.POST) public String upload(@RequestParam(value="file",required=false) MultipartFile file,HttpServletRequest request,RedirectAttributes redirectAttributes){ //获取文件名 String fileName = file.getOriginalFilename(); System.out.println("fileName:"+fileName); //获取文件的内容类型 String contentType = file.getContentType(); System.out.println("contentType:"+contentType); //它以多部分的形式返回参数的名称(参数的名称) String name = file.getName(); System.out.println("name:"+name); //获取文件的大小 long size = file.getSize(); System.out.println("size:"+size); //判断文件是否为空 boolean isEmpty = file.isEmpty(); System.out.println("isEmpty:"+isEmpty); //文件路径 String path = request.getServletContext().getRealPath("/upload"); System.out.println("path:"+path); if(!isEmpty){ File f = new File(path,fileName); if(!f.exists()){ f.mkdirs(); } //保存文件 try { file.transferTo(f); } catch (IllegalStateException | IOException e) { e.printStackTrace(); } redirectAttributes.addFlashAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName); System.out.println("保存文件的路径:"+f.getPath()); } return "redirect:/files/show"; } @RequestMapping(value="/show") public String showImage(){ return "file/image"; } }
upload.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>文件上传</title> </head> <body> <form action="${pageContext.request.contextPath }/files/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="提交"/> </form> </body> </html>
image.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>显示图片</title> </head> <body> <img alt="美女" src="${fileUrl }"> </body> </html>
spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方
1.form的enctype=”multipart/form-data” 这个是上传文件必须的
2.springmvc-servlet.xml中 <bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”/> 关于文件上传的配置不能少