上传多个文件

    /**
     * 上传文件
     * @param request
     * @param files
     * @return
     */
    
    @PostMapping("/pom-attendance-leaves/upload")
    @Timed
    public Map uploadMultiFile(HttpServletRequest request,@RequestParam("file") MultipartFile[] files) {
        Map map = pomAttendanceLeaveService.uploadMultiFile(request, files);
        return map;
    }
   /**
     * 上传文件
     * @param request
     * @param files
     * @return
     */
 @Override
    public Map uploadMultiFile(HttpServletRequest request, MultipartFile[] files) {
        //文件存放路劲     
        String uploadDir = request.getSession().getServletContext().getRealPath("/") + "/upload/";
        Map map = new HashMap<>();
        try {
            File dir = new File(uploadDir);
            //如果文件夹不存在,创建文件夹
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            //遍历文件上传
            for (int i = 0; i < files.length; i++) {
                if (files[i] != null) {
                    String url = executeUplaod(request,uploadDir, files[i]);
                    map.put("url", url);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 上传单个文件
     * @param uploadDir:文件夹路劲
     * @param file:文件
     */
    private String executeUplaod(HttpServletRequest request,String uploadDir, MultipartFile file) throws Exception{
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        UploadVm uploadVm = new UploadVm();
        //上传文件名
        String fileName = UUID.randomUUID() + suffix;
        String url = request.getLocalAddr() + ":" + request.getLocalPort();
        String fileUrl = url + "/upload" + "/" + fileName;
        uploadVm.setFileName(fileName);
        uploadVm.setFileUrl(fileUrl);
        File serverFile = new File(uploadDir + fileName);
        //存入服务端
        file.transferTo(serverFile);
        return fileUrl;
    }

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