Java 文件未重命名

Java 文件未重命名,java,spring,Java,Spring,我正在尝试实现这个Spring端点: private static String UPLOADED_FOLDER = "/opt/"; @PostMapping(value = "/upload", produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<StringResponseDTO> uploadFile(@RequestParam("file") MultipartFile fi

我正在尝试实现这个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));
    }
private static String上传_FOLDER=“/opt/”;
@PostMapping(value=“/upload”,products={MediaType.APPLICATION\u JSON\u value})
public ResponseEntity uploadFile(@RequestParam(“文件”)MultipartFile文件,RedirectAttributes RedirectAttributes,@RequestParam(“id”)Integer merchant_id)引发异常{
InputStream InputStream=file.getInputStream();
试一试{
byte[]bytes=file.getBytes();
文件目录=新文件(上传的\u文件夹,商户\u id.toString());
mkdirs()目录;
File newFile=新文件(目录,File.getOriginalFilename());
重命名(新文件(“merchant_logo.png”);
Files.write(newFile.toPath(),字节);
redirectAttributes.addFlashAttribute(“消息”,
“您已成功上载“+”文件。getOriginalFilename()+””;
}捕获(IOE异常){
e、 printStackTrace();
}
返回ResponseEntity.ok(新的StringResponseDTO(原始名称));
}

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

尝试将
新文件(“merchant\u logo.png”)
更改为
新建文件(目录,“merchant_logo.png”)
将文件写入正确的目录


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

Am使用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() + "'");
    }
@PostMapping(value=“/upload”,products={MediaType.APPLICATION\u JSON\u value})
公共响应上载文件(@RequestParam(“文件”)多部分文件,
RedirectAttributes RedirectAttributes,@RequestParam(“id”)Integer merchantId)引发异常{
试一试{
File directory=新文件(properties.getFileUploadDir(),merchantId.toString());
mkdirs()目录;
路径writeTargetPath=Files.write(
path.get(directory.getAbsolutePath(),file.getOriginalFilename()).toAbsolutePath(),
file.getBytes(),StandardOpenOption.CREATE\u NEW);
Path filetomovpath=Path.get(properties.getFileUploadDir(),merchantId.toString(),“merchant_logo.png”);
Path movedPath=Files.move(writeTargetPath、fileToMovePath、StandardCopyOption.REPLACE_EXISTING);
info(“movedPath:{}”,movedPath.toAbsolutePath());
redirectAttributes.addFlashAttribute(“消息”,
“已成功上载“+”文件。getOriginalFilename()+”);
}捕获(IOE异常){
log.error(“IOException:{}”,e);
返回ResponseEntity.ok(“上载失败””+file.getOriginalFilename()+“”);
}
返回ResponseEntity.ok(“已成功上载“+”文件.getOriginalFilename()+”);
}

renameTo
如果目标文件已存在,则可能无法工作,请先尝试删除它。重命名文件时,请尝试在
renameTo
方法中使用新名称保留正确的文件路径。此代码很奇怪。您可以创建一个包含新内容的新文件,然后删除旧文件。或者我遗漏了什么?你能试试下面的代码而不是重命名Path source=Path.get(“/Users/suman.das/Downloads/data1.csv”);文件.move(source、source.resolvessibling(“data1.csv”),替换现有文件;此外,您的代码非常奇怪(重命名文件.getOriginalFilename()现有文件,然后覆盖它,newFile和“merchant_logo.png”位于不同的目录中,“rename”无法处理),您的代码非常不安全!在未正确验证的情况下,切勿将(不安全的)输入直接用作文件名。外部攻击者可以通过您的方法访问应用程序能够访问的任何文件!我无法解析
属性
。我需要导入什么?我得到错误java.nio.file.filealreadyexistException:/opt/1/download.png如何覆盖旧文件?1。我不是硬编码上传的文件夹值,而是从属性文件中获取该值。2.我试过windows,没有这样的问题,你正在试Linux,你能验证你的文件夹权限吗。