• 首页
  • 邻居
  • 关于
  • 归档
  • 搜索
  • 夜间模式
    ©2020-2026  我的学习笔记 Theme by OneBlog

    我的学习笔记博客

    搜索
    标签
    # 随笔 # Java # 教程 # openwrt # Mysql # SQL # 爬虫 # post # Js调优 # MAVEN
  • 首页>
  • 随笔>
  • 正文
  • MultipartFile的transferto报错IO路径错误

    2024年02月04日 1.2 k 阅读 0 评论 1217 字

    问题描述:

    在使用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();
        }
    
    本文著作权归作者 [ admin ] 享有,未经作者书面授权,禁止转载,封面图片来源于 [ 互联网 ] ,本文仅供个人学习、研究和欣赏使用。如有异议,请联系博主及时处理。
    取消回复

    发表留言
    回复

    首页邻居关于归档
    Copyright©2020-2026  All Rights Reserved.  Load:0.015 s
    京ICP备18019712号
    Theme by OneBlog V3.6.5
    夜间模式

    开源不易,请尊重作者版权,保留基本的版权信息。