文件未重命名

时间:2019-08-23 07:36:04

标签: java spring

我正在尝试实现此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));
    }

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

2 个答案:

答案 0 :(得分:2)

我正在使用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() + "'");
    }

答案 1 :(得分:0)

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

在写入新文件之前删除旧文件也可以避免出现此类问题。