在 Spring Boot 中将图像上传到特定路径时出错

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

尝试将图像上传到目录时出现此错误:

无法完成请求:java.lang.RuntimeException:java.io.IOException:java.io.FileNotFoundException:C:\ Users \ LANDRY \ AppData \ Local \ Temp omcat.8080.7917247661488050367\work\Tomcat\localhost\ROOT\uploads\profile-pictures\Abraham89_4de0ea79-7b60-466a-8df1-0c4266cacb5e.jpg(系统找不到指定的路径)。

同时这是方法:

private static final String UPLOAD_DIR = "/uploads/profile-pictures/";;
private static  final long MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
@Override
public void uploadProfilePicture(User curUser, MultipartFile file){
    String contentType = file.getContentType();
    assert contentType != null;
    if(contentType.equals("jpg") || contentType.equals("png")){
        throw new IllegalArgumentException("Invalid file type. Only jpeg and png are allowed");
    }
    System.out.println("after first condition");
    if(file.getSize() > MAX_FILE_SIZE){ 
        throw new IllegalArgumentException("File size exceeds the maximum allowed size (2MB)");
    }
    System.out.println("after second condition");
    String fileName = null;

    try {
        if (curUser.getProfilePicturePath() != null) { 
            Path oldFilePath = Paths.get(curUser.getProfilePicturePath().substring(1)); // Remove the leading "/"
            Files.deleteIfExists(oldFilePath);
        }
        System.out.println("In the try catch block");
        String fileExtension = contentType.equals("image/jpeg") ? "jpg" : "png";
        fileName = curUser.getId()+"_"+ UUID.randomUUID() +"."+ fileExtension;
        Path userUplaodPath = Paths.get(UPLOAD_DIR + curUser.getUsername());
        if(!Files.exists(userUplaodPath)){
            Files.createDirectories(userUplaodPath);
        }
        System.out.println("Still there though");
        Path filePath = userUplaodPath.resolve(fileName);
        file.transferTo(filePath.toFile());
        System.out.println("File added to  system path");
        curUser.setProfilePicturePath("/" + UPLOAD_DIR + curUser.getUsername() + "/" + fileName);
        System.out.println("file added the database");
        userRepository.save(curUser);
        System.out.println("file saved successfully");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

我需要帮助

java spring-boot file-upload io
1个回答
0
投票

您应该在磁盘上定义一个可以保存文件的特定位置(已经存在)。尽量不要在 Servlet 容器内使用相对路径,因为不能保证底层文件系统始终看起来相同。 然后部署应用程序的人将需要负责提供此路径。 (在应用程序启动时验证属性是否已设置是有意义的,如果没有设置则快速失败)

相反,您应该从属性或类似的内容中读取绝对文件位置,上传的文件将存储在其中,例如:

uploaded.files.path=C:\Users\me omcat\uploads

然后您可以使用该属性构建所需文件的绝对路径。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.