如标题,我在使用spring boot上传文件的时候编写了如下代码:
然后debug出现如下信息:
最后执行上传的时候(file.transferTo(dest))报错:
错误原因:
查找这个方法:
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
this.part.write(dest.getPath());
}
进入这个write:
@Override
public void write(String fileName) throws IOException {
File file = new File(fileName);
if (!file.isAbsolute()) {
file = new File(location, fileName);
}
try {
fileItem.write(file);
} catch (Exception e) {
throw new IOException(e);
}
}
这时候我们看到如果!file.isAbsolute()
成立,也就是我们没有使用绝对路径,那么file = new File(location,fileName);
会在原来的基础上加上location路径.这就是原因所在。
我的解决方式是:
此时需要导入依赖:
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.2</version> </dependency>
大功告成