1、通過commons-fileupload和commons.io來實現。
導入相關JAR包: commons.fileupload-1.2.0.jar和commons.io-1.4.0.jar
2、配置springmvc的配置解析器
<bean id="multipartResolver" class= "org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="1048576000"></property> <property name="maxInMemorySize" value="40960"></property> </bean>
3、配置jsp頁面
<body> <form action="upload.do" method="post" enctype="multipart/form-data"> file:<input type="file" name="file"/> <input type="submit" value="上傳"/> </form> </body>
4、Controller代碼
@RequestMapping("/upload") public String fileupload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest req) throws IOException{ //獲取文件名 //file.getOriginalFilename(); //獲取上傳文件的路徑 String path = req.getRealPath("/fileupload"); InputStream is = file.getInputStream(); OutputStream os = new FileOutputStream(new File(path,file.getOriginalFilename())); int len = 0; byte[] buffer = new byte[400]; while((len=is.read(buffer))!=-1){ os.write(buffer, 0, len); } os.close(); is.close(); return "/index.jsp"; }
批量上傳的代碼
@RequestMapping("/batch") public String fileupload(@RequestParam("file") CommonsMultipartFile file[], HttpServletRequest req) throws IOException{ //獲取文件名 //file.getOriginalFilename(); //獲取上傳文件的路徑 String path = req.getRealPath("/fileupload"); for(int i =0;i<file.length;i++){ InputStream is = file[i].getInputStream(); OutputStream os = new FileOutputStream(new File(path,file[i].getOriginalFilename())); int len = 0; byte[] buffer = new byte[400]; while((len=is.read(buffer))!=-1) os.write(buffer, 0, len); os.close(); is.close(); } return "/index.jsp"; }