MULTIPARTFILE 上传文件

controller层

 public @ResponseBody
    Object uploadEditorImg(@RequestParam("img") MultipartFile files[], HttpServletRequest request) {
    
    
    	// 获取项目在系统盘中的绝对路径。
        String sPath = request.getRealPath("/");
        List<String> picUrls = new ArrayList<>();
        for (MultipartFile file: files) {
    
    
            try {
    
    
                String picUrl = imageService.uploadImg2FileSys(file, sPath,true);
                picUrls.add(picUrl);
            } catch (Exception e) {
    
    
                e.printStackTrace();
                return buildError("文件上传出错"+e.getMessage());
            }
        }
        return buildSucces(picUrls);
    }
  public String uploadImg2FileSys(MultipartFile file, String sPath, Boolean isRandomName) {
    
    
        // 添加uuid
        String fileName;
        if (isRandomName) {
    
    
            fileName = UUID.randomUUID() + file.getOriginalFilename();
        } else {
    
    
            fileName = file.getOriginalFilename();
        }
        //从配置的参数中获取图片保存的相对位置
        String imgUploadRelativePath = "upload/img/afc/nodeCategory/";
        //获取项目的绝对路径,来得到WebServer的根目录的绝对路径
        String pathname = sPath + imgUploadRelativePath;
        //创建目录
        File newfile1 = new File(pathname);
        if (!newfile1.exists()) {
    
    
            newfile1.mkdirs();
        }
        File imgFile = new File(newfile1, fileName);
        try {
    
    
            // 文件存储, 将文件存储到项目中
            file.transferTo(imgFile);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return "/" + imgUploadRelativePath + fileName;
    }

猜你喜欢

转载自blog.csdn.net/qq_41948178/article/details/107787001