gpt4 book ai didi

java - 覆盖 png 文件

转载 作者:行者123 更新时间:2023-12-02 01:20:55 27 4
gpt4 key购买 nike

我想覆盖上传的文件。我尝试了这段代码:

@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() + "'");

}

但我收到错误:

java.nio.file.FileAlreadyExistsException: /opt/1/download.png

你知道如何在每次上传文件时覆盖同名的旧文件吗?

最佳答案

API documentation StandardOpenOption.CREATE_NEW 说:

Create a new file, failing if the file already exists.

StandardOpenOption.CREATEStandardOpenOption.TRUNCATE_EXISTING 结合使用:

Path writeTargetPath = Files.write(
Paths.get(directory.getAbsolutePath(), file.getOriginalFilename()).toAbsolutePath(),
file.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

关于java - 覆盖 png 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57711851/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com