代码如下:
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam(value = "uploadDirectory") String uploadDirectory,
@RequestParam("fileName") MultipartFile fileName) {
try {
// 确保文件不为空
if (fileName.isEmpty()) {
return ResponseEntity.badRequest().body("No file selected to upload.");
}
String fileNameToSave = fileName.getOriginalFilename();
// 构建保存文件的完整路径
Path destinationFilePath = Paths.get(uploadDirectory, fileNameToSave);
// 创建目录(如果不存在)
Files.createDirectories(destinationFilePath.getParent());
// 保存文件到指定目录
Files.copy(fileName.getInputStream(), destinationFilePath, StandardCopyOption.REPLACE_EXISTING);
return ResponseEntity.ok("File uploaded successfully to: " + destinationFilePath.toAbsolutePath());
} catch (IOException ex) {
throw new MultipartException("Could not save file.", ex);
}
}