Perfree

Perfree

Perfree

简简单单的生活,安安静静的写博客~

54 文章数
71 评论数

SpringBoot-MultipartFile.transferTo路径错误问题

perfree
2019-04-18 / 0 评论 / 5005 阅读 / 0 点赞

今天写multipartFile转file,使用MultipartFile.transferTo(file)遇到了路径错误问题,代码如下:

/**
 * multipartFile转file
 * @param multipartFile
 * @param tempPath
 * @return File
 */
private static File getFile(MultipartFile multipartFile,String tempPath) {
    String fileName = multipartFile.getOriginalFilename();
    String filePath = tempPath;
    File file = new File(filePath + fileName);
    try {
        multipartFile.transferTo(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return file;
}

问题排查

报错信息大致如下:

java.io.IOException: java.io.FileNotFoundException: /tmp/tomcat.8587388778869943211.8888/work/Tomcat/localhost/ROOT/temp/1.jpg.PNG (No such file or directory)

这很明显的路径不对,接着又扒multipartFile.transferTo源码,结果发现如下一段代码:

public void transferTo(File dest) throws IOException, IllegalStateException {
    this.part.write(dest.getPath());
    if (dest.isAbsolute() && !dest.exists()) {
        FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest.toPath()));
    }
}

它竟然判断了下是否是绝对路径.................

问题解决

既然它要绝对路径,那我就给它绝对路径就好了,修改后的代码如下:

/**
 * multipartFile转file
 * @param multipartFile
 * @param tempPath
 * @return File
 */
private static File getFile(MultipartFile multipartFile,String tempPath) {
    String fileName = multipartFile.getOriginalFilename();
    String filePath = tempPath;
    File file = new File(filePath + fileName);
    try {
        multipartFile.transferTo(file.getAbsoluteFile());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return file;
}

到这里就没啥问题了,真的是......唉,一入编程深似海....

文章不错,扫码支持一下吧~
上一篇 下一篇
评论
来首音乐
最新回复
光阴似箭
今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月