spring mvc 文件上传
1. web页面通用
<form action="/Luobov/record/upload" method="post" enctype="multipart/form-data"> <input type="file" name="uploadfile" /> <input type="submit" value="upload" /> </form>
2.pom.xml需加入
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
3. springmvc的配置文件 要加入
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean>
4. Controller中处理
@RequestMapping(value = "/upload", method = RequestMethod.POST) public ModelAndView upload( @RequestParam("uploadfile") CommonsMultipartFile upfile, HttpServletRequest req) throws IOException { // |获取在Web服务器上的 绝对路径 System.out.println("come"); String path = req.getRealPath("/WEB-INF/static/"); System.out.println(path); // |获取输入流 InputStream is = upfile.getInputStream(); // |文件输出流 OutputStream os = new FileOutputStream(new File(path,upfile.getOriginalFilename())); System.out.println("come0"); // |循环写入 int length = 0; byte[] buffer = new byte[128]; while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); } System.out.println("come1"); is.close(); os.close(); // ===渲染=== System.out.println("come2"); // ModelAndView mView = new ModelAndView(); // mView.setViewName("upload"); // |返回至渲染器 return null; }
浙公网安备 33010602011771号