一. 点睛
文件上传是一个项目里经常要用到的功能,Spring
MVC
通过配置一个MultipartResolver
来上传文件。
在Spring
的控制器中,通过MultipartFile file
来接收文件,通过MultipartFile[] files
接收多个文件上传。
二. 示例
1. 添加文件上传依赖
<!-- file upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 非必需,可简化IO操作 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
2. 增加上传页面upload.jsp。
在src/main/resources/views
下新建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>upload page</title>
</head>
<body>
<div class="upload">
<form action="upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/><br/>
<input type="submit" value="上传">
</form>
</div>
</body>
</html>
3. 添加转向到upload页面的ViewController
在文件MyMvcConfig
的addViewControllers
方法里面增加下面的转向配置,代码如下:
registry.addViewController("/toUpload").setViewName("/upload");
添加完成之后的代码如下所示:
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("/index");
registry.addViewController("/toUpload").setViewName("/upload");
}
4. MultipartResolver配置
在文件MyMvcConfig
中增加下面的代码,提供对上传文件的支持:
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1000000);
return multipartResolver;
}
5. 控制器
package org.light4j.springMvc4.web;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
String upload(MultipartFile file) {// ①
try {
FileUtils.writeByteArrayToFile(new File("e:/upload/" + file.getOriginalFilename()),file.getBytes()); // ②
return "ok";
} catch (IOException e) {
e.printStackTrace();
return "wrong";
}
}
}
代码解释:
① 使用
MultipartFile file
接受上传的文件。
② 使用FileUtils.writeByteArrayToFile
快速写文件到磁盘。
6. 运行
访问http://localhost/springMvc4.x-fileUpload/toUpload
,效果如下图所示:
单击”上传”按钮之后,上传文件之后页面显示ok
,如下图所示:
查看f:/upload/
文件夹下面增加了刚刚上传的文件,如下图所示:
三. 源代码示例:
公众号ID:longjiazuoA

未经允许不得转载:人生设计师 » SpringMvc4.x高级配置(一):文件上传配置