Spring Boot 文件上传问题 - 无法存储文件错误仅在几天后发生

问题描述 投票:0回答:2

我有一个使用 Java Spring Boot 2.4.2 创建的 RESTful API。

我最近遇到的主要问题之一是,分段文件上传工作正常,但相同的代码在几天后将无法工作。重新启动 RESTFul JAR 应用程序后它将恢复工作。

Postman中显示的错误: 无法存储文件。错误

相关代码在这里:

try {
        FileUploadUtil.saveFile(uploadPath, file.getOriginalFilename(), file);
    } catch (IOException e) {
        throw new RuntimeException("Could not store the file. Error: " + e.getMessage());
    }

还有 FileUploadUtil 类:

public class FileUploadUtil {

public static void saveFile(String uploadDir, String fileName, MultipartFile multipartFile) throws IOException {
    Path uploadPath = Paths.get(uploadDir);

    if (!Files.exists(uploadPath)) {
        Files.createDirectories(uploadPath);
    }

    try (InputStream inputStream = multipartFile.getInputStream()) {
        Path filePath = uploadPath.resolve(fileName);
        Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException ioe) {
        throw new IOException("Could not save uploaded file: " + fileName, ioe);
    }
}

public static File fileFor(String uploadDir, String id) {
    return new File(uploadDir, id);
}}

而调用上面代码第一部分的主要POST API方法头是:

    @PostMapping(value = "/clients/details/{clientDetailsId}/files/{department}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@PreAuthorize("hasAuthority('PERSONNEL') or hasAuthority('CUSTODIAN') or hasAuthority('ADMIN')")
public ResponseEntity<ClientDetails> createClientDetailsFiles(@PathVariable("clientDetailsId") long clientDetailsId,
        @PathVariable("department") String department,
        @RequestPart(value = "FORM_SEC_58", required = false) MultipartFile[] FORM_SEC_58_file,@RequestPart(value = "FORM_SEC_78", required = false) MultipartFile[] FORM_SEC_78_file,
        @RequestPart(value = "FORM_SEC_105", required = false) MultipartFile[] FORM_SEC_105_file,
        @RequestPart(value = "FORM_SEC_51", required = false) MultipartFile[] FORM_SEC_51_file,
        @RequestPart(value = "FORM_SEC_76", required = false) MultipartFile[] FORM_SEC_76_file)

还有 application.properties 方面:

spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=90MB
spring.servlet.multipart.max-request-size=90MB

谁能告诉我问题出在哪里吗?

java spring-boot file-upload multipart multipartfile
2个回答
0
投票

我遇到了同样的问题,它曾经是工作文件,但一段时间后,它停止工作。我几乎可以肯定您的问题是这样的,因为我们有相同的代码并且我们的场景是相同的。我想到的方法是:

调试

我添加了一条语句来打印错误以查看实际发生的情况,您当前所做的只是获取错误消息,而不是整个错误。所以改成:

try {
    FileUploadUtil.saveFile(uploadPath, file.getOriginalFilename(), file);
} catch (IOException e) {
    e.printStackTrace();
    throw new RuntimeException("Could not store the file. Error: " + e.getMessage());
}

实际问题

错误是

FileAlreadyExistsException
FileAlreadyExistsException

基本上这意味着您正在尝试上传同名文件两次。

解决方案

要解决此问题,您可以使用不同的方法。其中之一是为文件生成 UUID 并将其也存储在数据库中,以供以后访问。


-1
投票

其他答案对我不起作用,但以下答案确实解决了问题:

// unique directory name to avoid conflicts
String uniqueDirName = "pom_" + UUID.randomUUID();
System.out.println("directory name is"+uniqueDirName);

Path targetDirectory = Paths.get("C:", uniqueDirName);
if (!Files.exists(targetDirectory)) {
    Files.createDirectories(targetDirectory);
}

Path pomFilePath = targetDirectory.resolve("pom.xml");
File pomFile = pomFilePath.toFile();


multipartFile.transferTo(pomFile);


if (!pomFile.isFile()) {
    return "The provided path does not point to a valid file.";
}

try {
    if (pomFilePath.toFile().exists() && pomFilePath.toFile().delete()) {
        System.out.println("POM file deleted successfully.");
    } else {
        System.out.println("Failed to delete POM file.");
    }
    
    if (Files.isDirectory(targetDirectory) && Files.list(targetDirectory).findAny().isEmpty()) {
        Files.deleteIfExists(targetDirectory);
        System.out.println("Directory deleted successfully.");
    } else {
        System.out.println("Directory not empty or failed to delete.");
    }
} catch (IOException e) {
    e.printStackTrace();
}
© www.soinside.com 2019 - 2024. All rights reserved.