gpt4 book ai didi

java - 文件未重命名

转载 作者:行者123 更新时间:2023-11-30 01:46:54 27 4
gpt4 key购买 nike

我正在尝试实现这个 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() + "'");
}

关于java - 文件未重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57621740/

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