0

I am working in eclipse using Swing Jframe. I currently have an upload button, that when clicked I need for it to allow the user to browse for an image and upload (Technically copy and rename it) it to a folder within my Java project called images. I will then reference the the file paths at a later time and display the images. Any help would be amazing!

    JButton uploadButton = new JButton("Upload...");
    uploadButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //TODO
        }
    });
    uploadPanel.add(uploadButton, BorderLayout.SOUTH);
    return uploadPanel;
cap
  • 17
  • 3
  • *"Any help would be amazing!"* Any help related to what? I'm not sure what your problem is? Or if it's related to how to copy images, or how to rename them, or how to find them, or how to display them – Frakcool Nov 14 '19 at 18:56
  • @Frakcool Any help with how to upload an image using a button and save it to a folder within the same package as the java project. – cap Nov 14 '19 at 18:59
  • For better help sooner post a [mre] – Frakcool Nov 14 '19 at 19:37
  • try with this link, it has pretty good example for file chooser https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html – Swaraj Nov 14 '19 at 19:38

1 Answers1

0

Hope that this helps answer your question :)

// Choose file
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);

// Make sure that a file was chosen, else exit
if (result != JFileChooser.APPROVE_OPTION) {
    System.exit(0);
}

// Get file path
String path = fc.getSelectedFile().getAbsolutePath();

// Create folder "images" (variable success will be true if a folder was created and false if it did not)
File folder = new File("images");
boolean success = folder.mkdir();
// Get the destination of the folder and the new image (image.jpg will be the new name)
String destination = folder.getAbsolutePath() + File.separator + "img.jpg";

try {
    // Copy file from source to destination
    FileChannel source = new FileInputStream(path).getChannel();
    FileChannel dest = new FileOutputStream(destination).getChannel();
    dest.transferFrom(source, 0, source.size());

    // Close shit
    source.close();
    dest.close();

    System.out.println("Done");
} catch (IOException e) {
    e.printStackTrace();
}
BobLee
  • 52
  • 6