How to save a file uploaded by FileChooser to a directory in your project?

so as the title of the post states I'm asking for a way that I can say a file I uploaded using FileChooser to a directory in my project.

More specifically, I'm uploading images and I want to save them in my project so I can use them in the future. Here is an example code:

Controller:

package org.example;

import javafx.fxml.FXML;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;

import java.io.File;

public class PrimaryController {

    @FXML
    private ImageView image;

    @FXML
    void handleUploadImage() {

        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Image Files", "*.jpg", "*.jpeg", "*.png", "*.svg"));
        File file = fileChooser.showOpenDialog(null);
        if (file != null) {
            image.setImage(new Image(String.valueOf(file)));
        } else {
            System.out.println("It's null");
        }
    }
}

FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.Cursor?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>


<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" style="-fx-background-color: linear-gradient(to right, #1c92d2, #f2fcfe);" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.example.PrimaryController">
   <children>
      <ImageView fx:id="image" fitHeight="200.0" fitWidth="200.0" layoutX="200.0" layoutY="100.0" onMouseClicked="#handleUploadImage" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../../images/upload.png" />
         </image>
         <cursor>
            <Cursor fx:constant="HAND" />
         </cursor>
      </ImageView>
   </children>
</AnchorPane>

My directories:

image

I would like to save the image in /resources/images. How can I do so?



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation