项目在服务器上文件上传想放到jar包所在文件夹lib的同级文件夹dist的upload文件夹中,该如何实现
@RestController
@RequestMapping("/api/bbb")
public class TimeController {
@PostMapping("/upload")
public BaseResult upload(MultipartFile file){
//获取文件名
String fileName = file.getOriginalFilename();
//获取文件后缀名
/* String suffixName = fileName.substring(fileName.lastIndexOf("."));
//重新生成文件名
fileName = UUID.randomUUID()+suffixName;*/
//指定本地文件夹存储
String filePath = ".../dist/upload/";
try {
//将图片保存到static文件夹里
file.transferTo(new File(filePath+fileName));
String tarpath = "tar -xvf"+ fileName+"-.../dist/upload";
Process process = Runtime.getRuntime().exec(tarpath);
return new BaseResult("200","success","");
} catch (Exception e) {
e.printStackTrace();
return new BaseResult("400","failed","");
}
}
}
/**
* 保存文件工具类
* @param file 文件
* @param storagePath 保存地址
* @param fileName 文件名称
* @return
*/
public static Boolean saveFile( MultipartFile file, String storagePath, String fileName) throws Exception{
//检查当前有没有传入的目录 如果有则不创建 ,反之创建目录
Path path = Paths.get(storagePath);
Boolean isCreate = null;
if (!Files.exists(path)) {
//创建目录
Path directories = Files.createDirectories(path);
isCreate = createFile(file, fileName, directories);
} else {
isCreate = createFile(file, fileName, path);
}
return isCreate;
}
private static Boolean createFile(MultipartFile file, String fileName, Path directories) {
try {
//获取输入流
InputStream in = file.getInputStream();
FileOutputStream fileOut = new FileOutputStream(new File(directories + "\\" + fileName));
byte[] buf = new byte[1024 * 8];
while (true) {
int read = 0;
if (in != null) {
read = in.read(buf);
}
if (read == -1) {
break;
}
fileOut.write(buf, 0, read);
}
fileOut.flush();
fileOut.close();
in.close();
} catch (IOException e) {
return false;
}
return true;
}