1.springMVC实现多文件上传需要的包如图
2.webroot下的结构如图所示3.java代码:
1 package cn.lxc.controller; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 9 import javax.servlet.http.HttpServletRequest; 10 11 import org.springframework.stereotype.Controller; 12 import org.springframework.web.bind.annotation.RequestMapping; 13 import org.springframework.web.bind.annotation.RequestParam; 14 import org.springframework.web.multipart.commons.CommonsMultipartFile; 15 16 @Controller 17 public class UploadController { 18 @RequestMapping("/upload.do") 19 public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req){ 20 String path= req.getSession().getServletContext().getRealPath("http://www.likecs.com/"); 21 System.out.println(path); 22 String fileName=file.getOriginalFilename(); 23 try { 24 InputStream is = file.getInputStream(); 25 OutputStream os = new FileOutputStream(new File(path,fileName)); 26 int len=0; 27 byte[] buffer = new byte[400]; 28 while((len=is.read(buffer))!=-1){ //len为读取数据的字节长度 29 os.write(buffer, 0, len); //三个参数分别为输出的字节数组、数据起始偏移量,输出字节长度 30 } 31 os.close(); 32 is.close(); 33 34 } catch (IOException e) { 35 e.printStackTrace(); 36 } 37 return "redirect:/index.jsp"; 38 } 39 }