试了很多网上说的后台保存文件办法,但是打包成jar包后,保存文件就出错,终于自己在综合多个帖子后才有了以下代码
@RequestMapping(value = "/uploadPDF/{node_key}", method = RequestMethod.POST)
public ResultJson upload(@RequestParam("file") MultipartFile file, @PathVariable int node_key){
if (file.isEmpty()) {
return ResultJson.fail();
}
try {
File path=new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()){
path=new File("");
}
File upload = new File(path.getAbsolutePath(),"static/pdf/upload/"+node_key);
// System.out.println(path.getAbsolutePath());
if(!upload.exists()){
upload.mkdirs();
}
String filename = file.getOriginalFilename();
File pdfFile = new File(upload + "/"+ filename);
file.transferTo(pdfFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ResultJson.success("添加成功!");
}
在Jar包同级目录创建文件夹并存储文件,windows/linux通用
File path=new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()){
path=new File("");
}
File upload = new File(parentFile.getAbsolutePath(),"static/pdf/upload/”);
if(!upload.exists()){
upload.mkdirs();//创建各级目录对象
}
filename.....
//在upload目录创建相应文件对象
File pdfFile = new File(upload + "/"+ filename);
在Jar包上级目录创建文件夹并存储文件,windows/linux通用
File path=new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()){
path=new File("");
}
//path是一个抽象路径的文件对象,必须获取相应的绝对路径文件对象,才能获取附文件对象
File parentFile = path.getAbsoluteFile().getParentFile();
if(!parentFile.exists()){
parentFile.mkdir();
}
File upload = new File(parentFile.getAbsolutePath(),"static/pdf/upload/");
if(!upload.exists()){
upload.mkdirs();
}
贴一下有帮助的帖子:
https://www.cnblogs.com/yangming1996/p/6602086.html