transferto遇到的问题java.io.FileNotFoundException: C:\Users\Administrator\AppData\Local\Temp
上传路径地址被修改:
文件上传的路径,会在文件地址的前面添加上C:\Users\Administrator\AppData\Local\Temp,导致java.io.FileNotFoundException
原出错代码
@PostMapping("/uploadSingleFile")
public String uploadSingleFile(@RequestParam("file") MultipartFile multipartFile) {
// 获取上传文件的名称
String fileName = multipartFile.getOriginalFilename();
// 构造存放文件的父路径
File parent = new File("D:/file/main");
if (!parent.exists()){
parent.mkdir();
log.info("开始创建parent文件夹:{}",parent.getPath());
}
try {
// 构造存放文件的完整路径
String new_FileName = parent.getCanonicalPath()+File.separator+fileName;
File filePath = new File(new_FileName);
// 这里上传的路径出错
multipartFile.transferTo(filePath.getAbsoluteFile());
} catch (IOException e) {
log.error("{}",e);
log.error("程序错误,请重新上传");
e.printStackTrace();
} finally {
log.info("文件上传成功");
}
return fileName;
}
multipartFile.transferTo方法,上传的文件的路径会被添加多余的地址
解决办法:使用FileUtils.copyInputStreamToFile,该方法在commons-io下。
导包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
修改的代码
@PostMapping("/uploadSingleFile")
public String uploadSingleFile(@RequestParam("file") MultipartFile multipartFile) {
// 获取上传文件的名称
String fileName = multipartFile.getOriginalFilename();
File parent = new File("D:/file/main");
if (!parent.exists()){
parent.mkdir();
log.info("开始创建parent文件夹:{}",parent.getPath());
}
try {
String new_FileName = parent.getCanonicalPath()+File.separator+fileName;
File filePath = new File(new_FileName);
// 这里修改后的代码
// multipartFile.transferTo(filePath.getAbsoluteFile());
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), filePath);
} catch (IOException e) {
log.error("{}",e);
log.error("程序错误,请重新上传");
e.printStackTrace();
} finally {
log.info("文件上传成功");
}
return fileName;
}
后记
希望该文可以帮助到您~
感谢您能看到这里~
欢迎批评指正奥~