How to Upload a Picture in a Desktop Application in Java

Save

Java comes with a built-in set of tools for handling network connections and both reading and writing data to a server, provided you use standard Internet protocols like HTTP and FTP. In a few steps, you can create a fast application, with a graphical user interface, that will upload pictures to an existing FTP server.

  • Open your favorite text editor of Java development environment and paste the following into it:

    import java.awt.GridLayout;

    import java.awt.Label;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import java.io.BufferedOutputStream;

    import java.io.File;

    import java.io.FileInputStream;

    import java.net.URL;

    import java.net.URLConnection;

    import javax.swing.*;

    public class UploadForm extends JFrame implements ActionListener {

    File image;

    JTextField server = new JTextField("");

    JTextField username = new JTextField("");

    JTextField imagePath = new JTextField("");

    JButton imageBrowse = new JButton("Find Image");

    JPasswordField password = new JPasswordField("");

    JButton uploadButton = new JButton("Upload");

    public void actionPerformed(ActionEvent ae) {

    }

    public UploadForm() {

    }

    public static void main(String[] args) {

    }

    }

    This simple class skeleton imports all the classes that will be needed from the standard Java libraries, defines the three methods the application will use, and creates the needed user interface elements.

  • Paste the following into the "main" method:

        JFrame f = new UploadForm();

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    f.setVisible(true);

    Experienced Java programmers will recognize this as the standard method that provides the entrance into your program from the operating system. In this case, it does very little: it creates the frame that holds the graphical user interface, ensures that the program will shut down when the user closes the frame, and makes the frame visible to the user.

  • Paste the following into the "UploadForm" constructor (the "UploadForm()" method):

        imageBrowse.addActionListener(this);

    uploadButton.addActionListener(this);

    this.setSize(640,100);

    this.setLayout(new GridLayout(0,2));

    this.add(imagePath);

    this.add(imageBrowse);

    this.add(new Label("Server"));

    this.add(server);

    this.add(new Label("Username"));

    this.add(username);

    this.add(new Label("Password"));

    this.add(password);

    this.add(uploadButton);

    This sets up the look of the graphical user interface using the "GridLayout" manager. First, the two buttons in the user interface are told to send action events to this program's "actionPerformed" method. Then, the GridLayout manager is configured to arrange the user interface elements in a grid with two columns and an unlimited number of rows. And, finally, all the user interface elements are added. The order matters: the GridLayout starts at the top-leftmost grid position and fills the entire row before moving down to the next row.

  • Paste the following into the "actionPerformed" method:

        if (ae.getSource().equals(imageBrowse)) {

    String s;

    JFileChooser jfc = new JFileChooser();

    jfc.showDialog(jfc, "Choose an image file");

    s = jfc.getSelectedFile().getAbsolutePath();

    imagePath.setText(s);

    } else

    if (ae.getSource().equals(uploadButton)) {

    try {

    File f = new File(imagePath.getText());

    String urlString = "ftp://" + username.getText() + ":" + password.getText() + "@" + server.getText() + "/" + f.getName();

    URL url = new URL(urlString);

    URLConnection connection = url.openConnection();

    connection.setDoOutput(true);

    BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());

    FileInputStream in = new FileInputStream(f);

    byte[] buffer = new byte[1024];

    int i = 0;

    while ((i = in.read(buffer)) >= 0) {

    out.write(buffer, 0, i);

    }

    out.close();

    in.close();

    }catch (Exception e) {

    System.out.println(e.getMessage());

    }

    }

    This method is a little complex, because the actionPerformed method has to do two things. If the "imageBrowse" button is clicked, it must present users with a file chooser dialog to allow them to select an image file from their hard drive. And, on the other hand, if the "uploadButton" is clicked, it must open the file selected with the image browser, open an FTP connection to a server (using the URLConnection class), and write the data from the file to the web server.

Tips & Warnings

  • This code is functional, but lots of error checking is left out in order to get to the task at hand. Nonsensical file names and bad server names are not checked for.

References

  • Photo Credit Polka Dot RF/Polka Dot/Getty Images
Promoted By Zergnet

Comments

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!