1.使用commons-fileupload来实现,导入相关依赖
commons-fileupload commons-fileupload 1.3.2 复制代码 commons-io commons-io 2.6
2.jsp页面--用来上传文件
复制代码
3.控制器
@RequestMapping("/upload")public String fileupload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest req) throws IOException { //获取上传文件的路径 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";}复制代码
4.在springmvc-servlet.xml配置文件上传解析器
复制代码
5.扩展:实现多个文件上传
复制代码
|
@RequestMapping("/batch")public String fileupload(@RequestParam("file")CommonsMultipartFile file[],HttpServletRequest req) throws IOException { //获取上传文件的路径 String path=req.getRealPath("/fileupload"); for(int i=0;i