有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring boot java。尼奥。文件打开文件时出现NoSuchFileException。调用transferTo()

我最近继承了一个Java API,在文件上传方面遇到了麻烦。不幸的是,Java不是一种我有很多经验的语言,所以我有点被它难住了

正在接收MultiPartFile正常,我可以在临时目录中找到该文件,但当我尝试使用该文件时。transferTo()创建最终文件时,我只得到以下错误

java.nio.file.NoSuchFileException: C:\Users\myUser\AppData\Local\Temp\undertow3706399294849267898upload -> S:\Dev\PolicyData\Temp.xlsx

正如我提到的,temp undertow文件存在,S驱动器上的目录也存在(但没有temp.xlsx,因为我的理解是这应该由transferTo()创建)。到目前为止,我找到的任何解决方案都是使用绝对文件路径解决的

这是代码的简化版本,但错误保持不变

SpringBoot框架是“1.5.3.RELEASE”,运行Java 1.8.0131

    ResponseEntity handleFileUpload(@RequestPart(name = "file") MultipartFile file, @PathVariable Long stageFileTypeId) {
    if (!file.isEmpty()) {
        try {
            String filePath = "S:\\Dev\\PolicyData\\Temp.xlsx";
            log.info("Upload Path = {}", filePath);

            File dest = new File(filePath);
            file.transferTo(dest);

            return ResponseUtil.wrapOrNotFound(Optional.ofNullable(filePath));
        }
        catch (Exception ex) {
            log.error("An error has occurred uploading the file", ex);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    else {
        log.error("An error has occurred, no file was received");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

如果你需要更多信息,请告诉我

谢谢, 尼尔


共 (1) 个答案

  1. # 1 楼答案

    MultipartFile的API有点棘手。transferTo(文件)方法javadoc声明(粗体是我的):

    This may either move the file in the filesystem, copy the file in the filesystem, or save memory-held contents to the destination file. If the destination file already exists, it will be deleted first.

    If the target file has been moved in the filesystem, this operation cannot be invoked again afterwards. Therefore, call this method just once in order to work with any storage mechanism.

    Undertow实现似乎已经调用它将内存中上载的文件移动到“C:\Users\myUser\AppData\Loca\Temp\UnderTow37063992994849267898Upload”,因此另一个transferTo失败

    我在使用javax时遇到了同样的问题。servlet。http。在一艘有底拖的野蝇集装箱船上

    如果您使用的是Spring框架>;=5.1,您可以尝试多部分。transferTo(Path)方法,使用dest.toPath()

    或者您可以从inputStream复制,如下所示:

    try (InputStream is = multipartFile.getInputStream()) {
        Files.copy(is, dest.toPath());
    }