1 通过commons-fileupload来实现 导入相关jar包
commons-fileupload,commons-io
2 配置springmvc的配置解析器
mvc:
3 jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>My JSP 'index.jsp' starting page
4 controller代码
@Controllerpublic class FileUploadController { @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"; }