Spring MVC 文件上传

文件上传

    文件上传是项目开发中最常用的功能。为了能上传文件,必须将表单的 method 设置为 post,并将 enctype 设置为 multipart/form-data。只有在这种情况下,浏览器才会把用户选择的文件二进制数据发送给服务器。

    一旦设置了 enctype 为 multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据,而对于文件上传的处理则涉及在服务器端解析原始的 HTTP 响应。2003年,Apache Software Foundation 发布了开源的 Commons FileUpload 组件,其很快成为 Servlet/JSP 程序员上传文件的最佳选择。

    Servlet 3.0 规范已经提供了方法来处理文件上传,但这种上传需要在 Servlet 中完成。而 Spring MVC 则提供了更加简单的封装。

    Spring MVC 为文件上传提供了直接的支持,这种支持是即插即用的 MultipartResolver 实现的。Spring MVC 使用 Apache Commons FileUpload 技术实现了一个 MultipartResolver 实现类:CommonsMultipartResolver。因此,Spring MVC 的文件上传还需要依赖 Apache Commons FileUpload 的组件。

index.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>
<a href="toupload">去上传文件</a>
</body>
</html>

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>
<h2>文件上传</h2>
<form action="upload" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>文件描述:</td>
<td><input type="text" name="description" /></td>
</tr>
<tr>
<td>请选择文件:</td>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td><input type="submit" value="上传" /></td>
</tr>
</table>
</form>
</body>
</html>

UploadFile.java

package org.rjxh.www.controller;


import java.io.File;
import java.io.IOException;


import javax.servlet.http.HttpServletRequest;


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;


@Controller
public class UploadFile {

@RequestMapping(value="/toupload")
public String toupload() {
return "upload";
}

@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(HttpServletRequest request,
@RequestParam("description") String description,
@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
System.out.println(description);
//如果文件不为空,则写入上传路径
if(!file.isEmpty()) {
//上传路径
String uploadpath = request.getServletContext().getRealPath("/images/");
System.out.println("uploadpath"+uploadpath);
//上传文件名
String uploadfilename = file.getOriginalFilename();
File filepath = new File(uploadpath,uploadfilename);
System.out.println("filepath"+filepath);
//判断路径是否存在,如果不存在就创建一个
if(!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件夹当中
File dir = new File(uploadpath+File.separator+uploadfilename);
System.out.println("dir"+dir);
file.transferTo(dir);
return "success";
}else {
return "error";
}
}
}
web.xml

<?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" 
id="WebApp_ID" version="3.0">
<!-- Spring MVC 前端控制器-->
<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:springmvc-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

springmvc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 扫描到有注解,就注册为bean -->
<context:component-scan base-package="org.rjxh.www.controller" />
    <!-- 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/pages/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<!-- 文件上传解析器,最大能上传 10MB 文件 ,请求的编码格式要和jsp的pageEncoding一致-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10485760"></property>  
    <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
</beans>

由于使用 Maven来构建项目,以下为 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.rjxh.www</groupId>
  <artifactId>springmvcuploadfile</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
  <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.2</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aop</artifactId>
   <version>4.2.5.RELEASE</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
   <version>4.2.5.RELEASE</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>4.2.5.RELEASE</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>4.2.5.RELEASE</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-expression</artifactId>
   <version>4.2.5.RELEASE</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>4.2.5.RELEASE</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>4.2.5.RELEASE</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.2</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.5</version>
</dependency>
  </dependencies>
</project>
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值