springMVC - 文件上传
1. 配置环境
pom.xml 中添加依赖
<dependencies> 里面添加:
<!-- 文件上传时使用的jar包--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
配置srpingmvc.xml, 在<beans>中添加
<!-- 配置文件上传解析器 --> <!-- id的值是固定的--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="104857600" /> <property name="maxInMemorySize" value="4096" /> <property name="defaultEncoding" value="UTF-8"></property> </bean>
2代码:
jsp部分
<!-- 上传文件 --> <div> <form action="/response/uploadTest" method="post" enctype="multipart/form-data"> <input type ="file" name="uploadFile" /> <button type="submit">上传</button> </form> </div>
controller部分
//文件上传 @RequestMapping("/uploadTest") public String uploadTest(HttpServletRequest request, MultipartFile uploadFile) { //MultipartFile 参数名字要与前台name一致 String path = "C:/Users/Administrator/Desktop/SpringMVC/data/"; //保存路径 String filename = UUID.randomUUID() + uploadFile.getOriginalFilename(); //确保文件名唯一,在前面拼上uuid try { uploadFile.transferTo(new File(path + filename)); //transferTo是spring提供的方法, 可以把文件上传到指定文件夹 } catch (IOException e) { e.printStackTrace(); } return "success"; }
输入:
选择文件然后点击上传
结果: