一、在pom.xml中加入依赖包:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
二、在spring配置文件中加入MultipartResolver处理器或者单独写个spring-upload.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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd"
default-lazy-init="true">
<description>Spring文件上传 </description>
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!-- 指定所上传文件的总大小不能超过20M。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="20000000"/>
</bean>
</beans>
三、form表单中一定要加上属性:enctype="multipart/form-data":
<form id="uploadForm" action="doUpload" method="post" enctype="multipart/form-data">
<input type="file" name="form" id="file" />
<input type="submit" value="上传" />
</form>
四、controller中接收所上传文件并保存:
package com.spring.demo.mvc;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/upload")
public class UploadController {
@RequestMapping("/show")
public String show() {
return "/demo/upload";
}
@RequestMapping("/doUpload")
public String doUpload(@RequestParam("file") MultipartFile file, Model model) {
// 保存图片
String fileName = file.getOriginalFilename();
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(
"C:\\Users\\Public\\Desktop\\" + fileName));
} catch (IOException e) {
throw new RuntimeException("上传失败");
}
return "/demo/age";
}
}
为了便于大家学习,项目将被开源在我的github上:
项目地址:https://github.com/gubaijin/buildmavenweb