Springmvc之文件上传
相关pom依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
springmvc.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 文件最大大小(字节) 1024*1024*50=50M-->
<property name="maxUploadSize" value="52428800"></property>
<!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
jsp页面
<form action="/book/upload" method="post" enctype="multipart/form-data">
请选择文件:<input type="file" name="xxx"/>
<input type="submit" value="ok">
</form>
BookController
/**
* springmvc文件上传
* @param xxx
* @return red
*/
@RequestMapping("/upload")
public String upload(HttpServletRequest req,MultipartFile xxx){
String fileName=xxx.getOriginalFilename();
String contentype=xxx.getContentType();
try {
FileUtils.copyInputStreamToFile(xxx.getInputStream(),new File("E:/T226/SSM/src/main/webapp/static/images/"+fileName));
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/book/list";
}
映射
运行: