首页 > Web开发 > 详细

文件上传2

时间:2019-12-31 16:48:43      阅读:73      评论:0      收藏:0      [点我收藏+]
 1 @Controller
 2 public class UploadFileController {
 3     //上传文件
 4     @ResponseBody
 5     @RequestMapping(value = "/uploadFile")
 6     public String uploadFile(HttpServletRequest request,@Param("file") MultipartFile file) throws IOException {
 7         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
 8         String res = sdf.format(new Date());
 9         //服务器上使用
10        // String rootPath =request.getServletContext().getRealPath("/resource/uploads/");//target的目录
11         //本地使用
12         String rootPath ="/Users/liuyanzhao/Documents/uploads/";
13         //原始名称
14         String originalFilename = file.getOriginalFilename();
15         //新的文件名称
16         String newFileName = res+originalFilename.substring(originalFilename.lastIndexOf("."));
17         //创建年月文件夹
18         Calendar date = Calendar.getInstance();
19         File dateDirs = new File(date.get(Calendar.YEAR)
20                 + File.separator + (date.get(Calendar.MONTH)+1));
21         //新文件
22         File newFile = new File(rootPath+File.separator+dateDirs+File.separator+newFileName);
23         //判断目标文件所在的目录是否存在
24         if(!newFile.getParentFile().exists()) {
25             //如果目标文件所在的目录不存在,则创建父目录
26             newFile.getParentFile().mkdirs();
27         }
28         System.out.println(newFile);
29         //将内存中的数据写入磁盘
30         file.transferTo(newFile);
31         //完整的url
32         String fileUrl =  "/uploads/"+date.get(Calendar.YEAR)+ "/"+(date.get(Calendar.MONTH)+1)+ "/"+ newFileName;
33         Map<String,Object> map = new HashMap<String,Object>();
34         Map<String,Object> map2 = new HashMap<String,Object>();
35         map.put("code",0);//0表示成功,1失败
36         map.put("msg","上传成功");//提示消息
37         map.put("data",map2);
38         map2.put("src",fileUrl);//图片url
39         map2.put("title",newFileName);//图片名称,这个会显示在输入框里
40         String result = new JSONObject(map).toString();
41         return result;
42     }
43 }

文件上传2

原文:https://www.cnblogs.com/yanghaoyu0624/p/12124890.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!