Spring MVC实现文件上传

时间:2023-03-09 02:59:17
Spring MVC实现文件上传

基础准备:


Spring MVC为文件上传提供了直接支持,这种支持来自于MultipartResolver。Spring使用Jakarta Commons FileUpload技术实现了一个MultipartResolver:CommonsMultipartResolver。

Spring MVC上下文中默认没有装配MultipartResolver,因此我们需要配置它。

    <!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="52428800"></property>
<property name="uploadTempDir" value="temp"></property>
</bean>

上面设置了文件编码为"UTF-8",设置了最大上传大小为50M,设置了上传文件的临时目录为Web目录下的temp。

控制器:


有了MultipartResolver,就可以在Controller中使用文件上传功能了。Spring MVC将上传文件绑定到MultipartFile对象上。MultipartFile提供了获取上传文件内容、文件名等内容,通过其transferTo()方法可以将文件储存到硬盘中:

    /**
* @描述 文件上传演示操作
* @时间 2013-7-26 下午5:17:42
*/
@ResponseBody
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public String doFileUpload(@RequestParam String desc, @RequestParam MultipartFile file)
throws IllegalStateException, IOException {
if (!file.isEmpty()) {
String path = ProjectUtil.getMavenWebProjectPath() + "runtime";
ProjectUtil.createDir(path);
file.transferTo(new File(path + "/" + file.getOriginalFilename()));
} else {
return "fail";
}
return SUCCESS;
}

这里使用了工具类中(ProjectUtil)的两个方法:

    /**
* @描述 Maven项目中,获取项目路径
* @时间 2013-7-26 下午5:13:02
* @return 项目路径。如:D:\kuaipan\springmvc\
*/
public static String getMavenWebProjectPath() {
Resource resource = new ClassPathResource("./");
String filePath = "";
try {
filePath = resource.getFile().getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
filePath = filePath.substring(0, filePath.indexOf("target"));
return filePath;
}
    /**
* 创建目录
*/
public static void createDir(String filePath) {
File myFile = new File(filePath);
if (!myFile.exists()) {
myFile.mkdirs();
}
}

页面:


页面上,就是一个表单,然后一个文件字段和描述字段。需要注意的是<form>上要有enctype="multipart/form-data"属性定义。