springmvc 上传文件

来源:互联网 发布:炒白银软件 编辑:程序博客网 时间:2024/06/05 22:47

springmvc上传文件使用的是apache的文件上传,需要包文件commons-io-2.4.jar,commons-fileupload-1.3.1.jar

1、前端jsp,enctype="multipart/form-data" 

<form action="uploadfile" method="post" enctype="multipart/form-data" >
<input type="file" name="file" value="上传"/>
<input type="submit" value="提交"/>
</form>

2、配置文件

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过800KB......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="8000000" />
</bean>

3、controller

@RequestMapping(value = "/uploadfile")
public String uploadfile(@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request) throws IOException {
System.out.println(file.getName());
String fileName = file.getOriginalFilename();
System.out.println(fileName);
String path = "D:\\svn";
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
return "hello";
}

其中@RequestParam(value = "file", required = false) 必须有,否则会出现异常

org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.multipart.MultipartFile]: Specified class is an interface

0 0
原创粉丝点击