spring 上传图片

 1 @RequestMapping(value = "/upload",method = RequestMethod.POST)
 2     public String upload(@RequestParam(value = "file", required = false) MultipartFile file){
 3         // 判断文件是否为空
 4         if (!file.isEmpty()) {
 5             // 文件保存路径
 6             String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"+ file.getOriginalFilename();
 7            
 8             UUID uuid = UUID.randomUUID();
 9            
10             String filename = uuid + file.getOriginalFilename();
11             File targetFile = new File(filePath,filename);
12             if (!targetFile.exists()) {
13 
14                 try {
15                     targetFile.createNewFile();
16                 } catch (IOException e) {
17                     e.printStackTrace();
18                 }
19             }
20             // 转存文件
21             try {
22                 file.transferTo(targetFile);
23             } catch (IOException e) {
24                 e.printStackTrace();
25             }
26            
27         }
28         return "upload";
29     }

 

posted @ 2015-11-07 16:09  Tcool  阅读(434)  评论(0编辑  收藏  举报