首页 > Web开发 > 详细

上传文件

时间:2019-12-17 23:25:44      阅读:93      评论:0      收藏:0      [点我收藏+]
@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);
    }

上传文件

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

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