文件未重命名



我正在尝试实现这个 Spring 端点:

private static String UPLOADED_FOLDER = "/opt/";
@PostMapping(value = "/upload", produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<StringResponseDTO> uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes, @RequestParam("id") Integer merchant_id) throws Exception {
InputStream inputStream = file.getInputStream();
try {
byte[] bytes = file.getBytes();
File directory = new File(UPLOADED_FOLDER, merchant_id.toString());
directory.mkdirs();
File newFile = new File(directory, file.getOriginalFilename());
newFile.renameTo(new File("merchant_logo.png"));
Files.write(newFile.toPath(), bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok(new StringResponseDTO(originalName));
}

一般的想法是重命名文件并覆盖具有相同名称的先前文件。但由于某种原因,它不起作用。我得到了旧文件内容。知道为什么吗?

我使用的是java 1.8,也许这会帮助你。

@PostMapping(value = "/upload", produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes, @RequestParam("id") Integer merchantId) throws Exception {
try {
File directory = new File(properties.getFileUploadDir(), merchantId.toString());
directory.mkdirs();
Path writeTargetPath = Files.write(
Paths.get(directory.getAbsolutePath(), file.getOriginalFilename()).toAbsolutePath(),
file.getBytes(), StandardOpenOption.CREATE_NEW);
Path fileToMovePath = Paths.get(properties.getFileUploadDir(), merchantId.toString(), "merchant_logo.png");
Path movedPath = Files.move(writeTargetPath, fileToMovePath, StandardCopyOption.REPLACE_EXISTING);
log.info("movedPath: {}", movedPath.toAbsolutePath());
redirectAttributes.addFlashAttribute("message",
"Successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
log.error("IOException: {}", e);
return ResponseEntity.ok("Upload failed'" + file.getOriginalFilename() + "'");
}
return ResponseEntity.ok("Successfully uploaded'" + file.getOriginalFilename() + "'");
}

尝试将new File("merchant_logo.png")更改为new File(directory,"merchant_logo.png")在正确的目录中写入文件。

此外,在编写新文件之前删除旧文件有助于避免出现此类问题。

最新更新