MultipartFile的transferto报错IO路径错误 Published on Feb 4, 2024 in 随笔 with 0 comment 问题描述: 在使用MultipartFile.transferto准备保存上传文件的时候报错IO路径错误(IO路径不存在),但是我肯定我指定的路径是存在的 出现原因: MultipartFile.transferto(file)该方法内参数需要的是绝对路径而不是相对路径,如果我们传入的是相对路径的话,那么该方法就会去tomcat内的webapp下去寻找该相对路径。这样肯定是找不到对应路径的,所以会出现该报错 解决方案: 选择传入绝对路径而不是相对路径 file类有获取绝对值的方法getCanonicalPath() 修改后的代码 ```java @PostMapping("/upload") public myResult upLoadFiles(MultipartFile[] files, HttpServletRequest request) throws IOException { // 1.获取所有文件的文件名 分配文件路径 String parentPath = "uploadFiles"; File parent = new File(parentPath); if (!parent.exists()){ parent.mkdir(); log.info("开始创建parent文件夹:{}",parent.getPath()); } for (MultipartFile file : files){ String fileName = file.getOriginalFilename(); String new_FileName = parent.getCanonicalPath()+File.separator+fileName; log.info(new_FileName); try { file.transferTo(new File(new_FileName)); log.info("文件{}上传成功!",new_FileName); } catch (IOException e) { throw new RuntimeException(e); } } return new myResult().ok(); } ``` 本文由 admin 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。