SpringMvc文件上传

1.导入相关架包    Fileupload

 2.  网页

表单必须是post提交,编码必须是multipart/form-data  文件上传文本框必须起名。

 

 3.在springmvc中配置文件上传解析器

4.在控制层处理代码

 1 public class UploadFilecontroller {
 2     @RequestMapping("file")                    //HttpServletRequest为了获取上传文件的路径
 3     public String upload(MultipartFile photo,HttpServletRequest request) {//MultipartFile photo:把上传的文件封装到MultipartFile中
 4         //1.获取文件上传的真实保存路径
 5         String realPath = request.getServletContext().getRealPath("/upload");
 6         System.out.println(realPath);
 7         //2.创建一个文件对象
 8         File file=new File(realPath);
 9         if(!file.exists()) {//如果该路径不存在
10             file.mkdirs();
11         }
12         //3.获取文件名
13         String name =System.currentTimeMillis()+ photo.getOriginalFilename();
14         
15         //新建文件对象
16         File targetFile=new File(realPath+"/"+name);
17         
18         try {
19             //4.把文件写入到指定的目录下
20             FileUtils.writeByteArrayToFile(targetFile, photo.getBytes());
21         } catch (IOException e) {
22             // TODO Auto-generated catch block
23             e.printStackTrace();
24         }
25         return "redirect:index.jsp";
26     }
27 }
原文地址:https://www.cnblogs.com/mcl2238973568/p/11461621.html