java文件上传

多文件上传


  
// 创建目录
SimpleDateFormat sft = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/uploadsFd")
//  接收formData提交
    public String uploadsFd(HttpServletRequest req,
                            HttpServletResponse rsq,
                            @RequestParam(required = false, value = "files") MultipartFile[] files,
                            @RequestParam(required = false, value = "remark") String remark) {
        System.out.println("remark = " + remark);
        realPath = req.getServletContext().getRealPath("/img") + format;
        return upLoadedUrls(req, files, realPath);
    }

    private String upLoadedUrls(HttpServletRequest req, @RequestParam(required = false, value = "files") MultipartFile[] files, String realPath) {
        String reUrl = "";
        List urls = new ArrayList<>();
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        for (MultipartFile file : files) {
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            try {
                file.transferTo(new File(folder, newName));
                String url = req.getScheme() + "://" + req.getServerName()
                        + ":" + req.getServerPort() + "/img" + format + newName;
                System.out.println("url = " + url);
                urls.add(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return String.join(",",urls);
    }

单文件上传

@PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest req) {
        String format = sft.format(new Date());
        // 创建真实路径
        String realPath = req.getServletContext().getRealPath("/img") + format;
        File folder = new File(realPath);
        // 创建目录s
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        // 创建文件名
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try {
            // 保存文件
            file.transferTo(new File(folder, newName));
            String url = req.getScheme() + "://" + req.getServerName()
                    + ":" + req.getServerPort() + "/img" + format + newName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

你可能感兴趣的:(java文件上传)