MultipartFile的transferto报错IO路径错误

问题描述:

在使用MultipartFile.transferto准备保存上传文件的时候报错IO路径错误(IO路径不存在),但是我肯定我指定的路径是存在的

出现原因:

MultipartFile.transferto(file)该方法内参数需要的是绝对路径而不是相对路径,如果我们传入的是相对路径的话,那么该方法就会去tomcat内的webapp下去寻找该相对路径。这样肯定是找不到对应路径的,所以会出现该报错

解决方案:

选择传入绝对路径而不是相对路径

file类有获取绝对值的方法getCanonicalPath()

修改后的代码

@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();
    }
版权声明 ▶ 本网站名称:我的学习笔记
▶ 本文链接:https://ooolo.net/article/403.html
▶ 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行核实删除。
▶ 转载本站文章需要遵守:商业转载请联系站长,非商业转载请注明出处!!!

none
最后修改于:2024年02月04日 09:21

添加新评论

icon_mrgreen.pngicon_neutral.pngicon_twisted.pngicon_arrow.pngicon_eek.pngicon_smile.pngicon_confused.pngicon_cool.pngicon_evil.pngicon_biggrin.pngicon_idea.pngicon_redface.pngicon_razz.pngicon_rolleyes.pngicon_wink.pngicon_cry.pngicon_surprised.pngicon_lol.pngicon_mad.pngicon_sad.pngicon_exclaim.pngicon_question.png