我可以在项目的资源文件夹中看到图像,但我仍然收到无效的 url 错误

I can see the image in my project's resource folder but I am still getting an invalid url error

所以我有一个程序,用户可以在其中上传图片,然后将其和产品保存到网上商店。但是我遇到了一个非常奇怪的问题,其中 none 的文件名被识别。基本上,用户使用文件选择器在本地上传文件。我已经尝试将它保存到我的资源文件夹,我已经尝试将它保存到 resources/images,并且我已经尝试将它保存到 main/images 并且每次都发生同样的事情。用户 select 他们要上传的照片,我看到它转到了正确的文件夹,但是当用户单击上传并创建新产品时,会抛出一个错误,说 url 无效或资源无效不存在。事情是这样的。资源确实存在。我看着它出现在我的 Intellij 项目中 window。我什至将文件的路径打印到控制台,以防它去其他地方,但不,它是正确的文件路径。我想可能有一些奇怪的拼写错误,所以我将文件拖到终端,不,它是确切的文件路径。我快要疯了,想弄清楚这一点。

上传发生的地方

public class UploadItems {

    @FXML private TextField productName;
    @FXML private TextField quantityForSale;
    @FXML private TextField prices;
    @FXML private Image image;
    @FXML private Button imageUploadBtn;
    @FXML private Button uploadBtn;
    private MainController mainController;
    private File file;
    private ConnectToDb connectToDb = new ConnectToDb();
    private StoreHomePageController storeHomePageController;
    private final String fileLocation = "/Users/myname/IdeaProjects/AmeenazonOnlineStore/src/main/Images";

    public UploadItems(){
        mainController = new MainController();
        storeHomePageController = new StoreHomePageController(mainController);

    }
    @FXML
    private void initialize(){

        imageUploadBtn.setOnAction(e -> {
            uploadImageBtn();
        });
        uploadBtn.setOnAction(e -> {
            uploadBtn();

        });
    }
    private void uploadBtn(){
        String name = productName.getText();
        String otherFileLocation = "/Users/myname/IdeaProjects/AmeenazonOnlineStore/src/main/Images/";
        int quantity = Integer.parseInt(quantityForSale.getText());
        int price = Integer.parseInt(prices.getText());
        String filename = otherFileLocation + file.getName();

        if (!name.isEmpty() && quantity > 0 && price > 0){
            String query = " INSERT INTO products(name, price, quantity, filename)"
                    + " VALUES(?, ?, ?, ?)";
            try {
                PreparedStatement preparedStatement = connectToDb.getConn().prepareStatement(query);
                preparedStatement.setString(1, name);
                preparedStatement.setInt(2, price);
                preparedStatement.setInt(3, quantity);
                preparedStatement.setString(4, filename);

                if (checkTableForProduct()){
// error is thrown here because the filename is invalid. printing to the console right here will show the valid file name
                    storeHomePageController.addToVBoxList(new Product(name, price, quantity, filename));

                    System.out.println("product added... hopefully ");
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("Item Successfully Uploaded!");
                    alert.setHeaderText("You can now sell your stuff. We can't wait for our cut");
                    alert.setContentText("You better not stiff us or we'll send our goons out to get you!");
                    alert.showAndWait();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            } try {

                Window window = uploadBtn.getScene().getWindow();
                window.hide();
                FXMLLoader loader = new FXMLLoader(getClass().getResource("/StoreHomePageLayout.fxml"));
                loader.setController(new StoreHomePageController(mainController));
                Stage secondaryStage = new Stage();
                secondaryStage.setTitle("Ameenazon");
                secondaryStage.setHeight(800);
                secondaryStage.setWidth(800);
                Scene scene = new Scene(loader.load());
                secondaryStage.setScene(scene);
                secondaryStage.show();

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    private void uploadImageBtn(){
        String otherFileLocation = "/Users/myname/IdeaProjects/AmeenazonOnlineStore/src/main/Images/";
        Stage stage = new Stage();
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Select Image");

        file = fileChooser.showOpenDialog(stage);
        if (file != null){
            Path movefrom = FileSystems.getDefault().getPath(file.getPath());
            Path target = FileSystems.getDefault().getPath(otherFileLocation  +  file.getName());
            imageUploadBtn.getProperties().put(otherFileLocation, file.getAbsolutePath());
            System.out.println("image upload button ");
            try{
                Files.move(movefrom,target, StandardCopyOption.ATOMIC_MOVE);
                System.out.println("image moved");
            } catch (IOException ex){
                ex.printStackTrace();
            }
        }
    }

这是产品 class

public class Product {

    private String name;
    private String companyName;
    private double price;
    private int quantity;
    private String description;
    private ImageView imageView;
    private String fileName;
    private String info;
    private Image image;
 quantity, String description, Image image, String fileName, String info){
    public Product(String name, double price, int quantity, String fileNames)  {
        this.name = name;
        this.companyName = companyName;
        this.price = price;
        this.description = description;
        this.imageView = imageView;
        this.quantity = quantity;
        this.fileName = fileNames;
        System.out.println(this.fileName);
        System.out.println(fileNames);
// these both print the correct file path to the correct file which I can see in my project window 
        this.info = info;
        this.image = new Image(fileNames);
// a bunch of getters
}

所以是的,我不知道发生了什么。这是因为我在 FXML 初始化中设置了按钮操作吗?我可以看到 .png 文件已添加到我的项目中。当我在正确的文件夹中看到它时,我收到无效的 url 或资源不存在错误对我来说没有意义。我什至可以将文件的视频剪辑添加到正确的位置,然后说那里没有文件。

把产品添加到首页的方法就可以了。它在过去有效。实际上只是文件名给我一个错误。

谢谢

您是否尝试过将图像作为文件而不是字符串加载?

try {
    File pathToFile = new File("image.png");
    Image image = ImageIO.read(pathToFile);
} catch (IOException ex) {
    ex.printStackTrace();
}

Image 构造函数需要 URL,而不是文件名。你错过了一个计划;此外,有效的文件名可能无效 URLs.

使用 FilePath 的功能转换为 URL:

String filename = new File(otherFileLocation + file.getName()).toURI().toString();