zoukankan      html  css  js  c++  java
  • 文件上传2

     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 }
  • 相关阅读:
    (九十三)蓝牙的基本使用
    (九十二)加速计的用法(过期方法+新方法)
    (九十一)距离传感器的使用
    1060. Are They Equal (25)
    (九十)使用多个storyboard+代码实现控制器的分开管理
    (八十九)用AutoLayout实现动画和Label根据内容自动调整
    HDU 2013:蟠桃记
    HDU 2050:折线分割平面
    HDU 2042:不容易系列之二
    HDU 1465:不容易系列之一
  • 原文地址:https://www.cnblogs.com/yanghaoyu0624/p/12124890.html
Copyright © 2011-2022 走看看