// Controller
/**
* 文件上传
* 例:上传 xxx.jpg
* path=null D:\dev\aaa\xxx.jpg
* path=../ D:\dev\xxx.jpg
* path=D:\dev\aaa D:\dev\aaa\xxx.jpg
*
* @param file 文件
* @param path 上传文件路径
* @return
*/
@PostMapping("/upload")
public String upload(MultipartFile file, String path) throws IOException {
String filePath = "";
InputStream inputStream = null;
String fileName = file.getOriginalFilename();
// jar path
String basePath = FileUtil.jarParentPath() + File.separator;
String targetPath = StringUtils.isEmpty(path) ? basePath : path.contains("..") ? basePath + path : path;
try {
// Copy file to the target location (Replacing existing file with the same name)
Path fullPath = FileUtil.getFilePath(targetPath)
.resolve(Objects.requireNonNull(fileName));
inputStream = file.getInputStream();
Files.copy(inputStream, fullPath, StandardCopyOption.REPLACE_EXISTING);
filePath = fullPath.toString();
} catch (IOException ex) {
throw new RuntimeException("Could not store file " + fileName + ". Please try again!", ex);
} finally {
// 必须关闭流,否则出现异常:tomcat tmp 文件无法删除
assert inputStream != null;
inputStream.close();
}
return filePath;
}
// FileUtil
public static Path getFilePath(String basePath) {
return Paths.get(basePath).toAbsolutePath().normalize();
}
/**
* jar包所在路径
*
* @return 若无jar包,则是项目路径
*/
public static String jarParentPath() {
ApplicationHome h = new ApplicationHome();
File jarF = h.getSource();
return Optional.ofNullable(jarF).map(File::getParentFile).map(File::toString).orElse(h.toString());
}
feat-sb-upload
于 2023-07-10 19:04:41 首次发布