简体   繁体   中英

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

So I have a program where users can upload an image and then save it and the product to an online store. But I am having a very weird issue where none of the file names are recognized. Basically the user uses a file chooser to upload a file locally. I have tried it to my resources folder, I have tried it to resources/images, and I have tried saving it to main/images and every time the same thing happens. the users select the photo they want to upload, I watch it go to the correct folder but then when the user clicks upload and creates a new product, an error is thrown up saying invalid url or resource does not exist. here's the thing. the resource does exist. I watch as it appears in my Intellij project window. I even print the file's path to the console on the off chance it is going somewhere else but nope, it is the correct file path. I thought maybe there was some weird typo so I dragged the file to the terminal and nope it is the exact file path. I am going crazy trying to figure this out.

where the upload is happening

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();
            }
        }
    }

and here's the product 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
}

So yeah I have no idea what is going on. Is this because I am setting my button actions in my FXML initialize? I can see the .png file get added to my project. it does not make sense to me that I get an invalid url or resource does not exist error when I can see it... in the correct folder. I can even add a video clip of the file going to the right place and then saying there is no file there.

the method that adds the product to the homepage is fine. It has worked in the past. it is really only the filename that is giving me an error.

Thanks

Have you tried loading the image as a file, not as string?

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

The Image constructor expects an URL, not a file name. You're missing a scheme; Furthermore valid file names may not be valid URLs.

Use File 's or Path s functionality to convert to an URL:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM