本文共 1149 字,大约阅读时间需要 3 分钟。
在文件上传时,我们需要用到文件上传解析器,其实,它并不陌生,只是对httpServletRequest的一个扩展,使其能够更好的处理文件上传,扩展的接口名为:org.springframework.web.multipart.MultipartHttpServletRequest
先用一个类图看一下这个它的底层架构:
下面用代码层面看一下如何实现:
org.springframework.web.multipart.commons.CommonsMultipartResolver">
@Controller@RequestMapping("/file")public class UploadController { @RequestMapping(value="/upload") public String addUser(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest request) throws IOException{ System.out.println("fileName--->"+file.getOriginalFilename()); if (!file.isEmpty()) { try { //定义文件的路径 FileOutputStream os=new FileOutputStream("D:/"+new Date().getTime() +file.getOriginalFilename()); //上传文件 InputStream in=file.getInputStream(); int b=0; //如果文件内容部位空 while ((b=in.read())!=-1){ os.write(b); } os.flush();//刷新 os.close(); in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "/success"; }
注意:两处加红的字体必须一致