码迷,mamicode.com
首页 > Web开发 > 详细

上传文件

时间:2019-12-17 22:23:11      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:stp   class   format   tps   try   return   file   ret   cep   

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(MultipartFile file, HttpServletRequest request) {
        String path = localpath + "\\";
        String date = sdf.format(new Date());
        String routepath = path + date;
        String url = httpurl.getRequestPrefix(request);//项目地址
        String[] files = file.getOriginalFilename().split("\\.");//获取上传文件的后缀
        String filename = UUID.randomUUID().toString().replaceAll("-", "");//给文件重新命名
        String name = routepath + "\\" + filename + "." + files[1];
        String besuchurl = url + "/static/" + date.replaceAll("\\\\", "/") + "/" + filename + "." + files[1];//访问路径
        File file2 = new File(routepath);
        if (!file.isEmpty()) {//判断文件是否为空
            if (!file2.exists()) {//判断文件夹是否为空
                file2.mkdirs();
            } else {
                try {
                    file.transferTo(new File(name));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return besuchurl;
    }

上传多个文件

    @RequestMapping(value = "/uploads", method = RequestMethod.POST)
    public toJSON uploads(MultipartFile[] filees, HttpServletRequest request) {
        ArrayList list = new ArrayList();
        for (int i = 0; i < filees.length; i++) {
            String path = localpath + "\\";
            String date = sdf.format(new Date());
            String routepath = path + date;
            String url = httpurl.getRequestPrefix(request);//项目地址
            String[] files = filees[i].getOriginalFilename().split("\\.");//获取上传文件的后缀
            String filename = UUID.randomUUID().toString().replaceAll("-", "");//给文件重新命名
            String name = routepath + "\\" + filename + "." + files[1];
            String besuchurl = url + "/static/" + date.replaceAll("\\\\", "/") + "/" + filename + "." + files[1];//访问路径
            File file2 = new File(routepath);
            if (!filees[i].isEmpty()) {//判断文件是否为空
                if (!file2.exists()) {//判断文件夹是否为空
                    file2.mkdirs();
                } else {
                    try {
                        filees[i].transferTo(new File(name));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            fileurl fileurl=new fileurl();
            fileurl.setId(files[0]);
            fileurl.setUrl(besuchurl);
            list.add(fileurl);
        }
        return new toJSON("ok", "成功", list);
    }

上传文件

标签:stp   class   format   tps   try   return   file   ret   cep   

原文地址:https://www.cnblogs.com/xymaxbf/p/12057105.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!