java的Spring MVC 文件上传
1.引入jar包
2.把文件上传的bean加入到ioc容易中(就是配置spring-mvc文件)
3.写表单开始提交数据
4.控制器接收数据
---------------------------------------
1.一般上传文件需要用的jar包为(通过maven依赖更方便):
<!-- 上传组件包 --> <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> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency>
2.配置bean
<!-- 多部分文件上传 --> <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>
3.表单提交
<form name="input" action="${pageContext.request.contextPath}/data/uploadFile" method="post" enctype="multipart/form-data"> user: <input type="text" name="user" /> file: <input type="file" name="file" /> <input type="submit" value="Submit"> </form>
4.控制器处理(spring MVC处理器)已经处理好了,直接接收表单的内容即可
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public @ResponseBody String uploadFile(@RequestParam("user") String user,@RequestParam("file") CommonsMultipartFile file) throws IOException{ long startTime=System.currentTimeMillis();//用来检测程序运行时间 System.out.println(user);//表单的文本字段 System.out.println(file);//表单提交过来的文件 System.out.println("fileName:"+file.getOriginalFilename()); //1.获得io流 InputStream is = file.getInputStream(); //2.创建一个输出流,把获得的io流写到硬盘 OutputStream os = new FileOutputStream(new File("C:\1.txt")); byte[] bs = new byte[1024]; int len = -1; while((len = is.read(bs))!=-1) { os.write(bs,0,len); } os.close(); is.close(); return null; }