How To Create A Progress Popup For My Ftp Upload Java
- Details
- Written past
- Last Updated on 02 July 2019 | Impress Email
This tutorial walks you lot through steps of developing a Swing-based application that uploads files from local figurer to a remote FTP server. The awarding looks like this:
The following diagram describes workflow of the application:
The Swing customer application connects to the server via FTP protocol to transfer files. The FTP library to exist used is Apache Commons Net.
The post-obit class diagram depicts how the application is designed:
The main classes are:
-
- FTPUtility: implements FTP file upload functionality.
- UploadTask: executes the file upload chore in a background thread other than the Swing's upshot dispatcher thread (EDT), so the GUI won't become freezing.
- SwingFileUploadFTP: assembles user interface of the application. It allows users to specify FTP server information (host, port, username, countersign and upload destination), cull a file to be uploaded. Information technology shows a progress bar while the upload is taking identify.
For the classes JFilePicker and FileTypeFilter, its source lawmaking can be obtained from article File picker component in Swing. The FTPException is a custom exception grade.
Permit's look at implementation of each main class in details.
1. Code of FTPUtility class
package net.codejava.swing.upload.ftp; import java.io.File; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; /** * A utility grade that provides functionality for uploading files to a FTP * server. * * @writer www.codejava.cyberspace * */ public class FTPUtility { individual String host; private int port; private String username; private String countersign; individual FTPClient ftpClient = new FTPClient(); private int replyCode; private OutputStream outputStream; public FTPUtility(Cord host, int port, String user, String pass) { this.host = host; this.port = port; this.username = user; this.countersign = pass; } /** * Connect and login to the server. * * @throws FTPException */ public void connect() throws FTPException { try { ftpClient.connect(host, port); replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { throw new FTPException("FTP serve refused connectedness."); } boolean logged = ftpClient.login(username, countersign); if (!logged) { // failed to login ftpClient.disconnect(); throw new FTPException("Could not login to the server."); } ftpClient.enterLocalPassiveMode(); } catch (IOException ex) { throw new FTPException("I/O fault: " + ex.getMessage()); } } /** * Start uploading a file to the server * @param uploadFile the file to be uploaded * @param destDir destination directory on the server * where the file is stored * @throws FTPException if client-server communication error occurred */ public void uploadFile(File uploadFile, String destDir) throws FTPException { try { boolean success = ftpClient.changeWorkingDirectory(destDir); if (!success) { throw new FTPException("Could not modify working directory to " + destDir + ". The directory may not be."); } success = ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!success) { throw new FTPException("Could non set binary file type."); } outputStream = ftpClient.storeFileStream(uploadFile.getName()); } grab (IOException ex) { throw new FTPException("Mistake uploading file: " + ex.getMessage()); } } /** * Write an array of bytes to the output stream. */ public void writeFileBytes(byte[] bytes, int starting time, int length) throws IOException { outputStream.write(bytes, offset, length); } /** * Complete the upload operation. */ public void finish() throws IOException { outputStream.close(); ftpClient.completePendingCommand(); } /** * Log out and disconnect from the server */ public void disconnect() throws FTPException { if (ftpClient.isConnected()) { effort { if (!ftpClient.logout()) { throw new FTPException("Could non log out from the server"); } ftpClient.disconnect(); } grab (IOException ex) { throw new FTPException("Error disconnect from the server: " + ex.getMessage()); } } } }
This utility class is based on the FTP upload functionality described in the tutorial Upload files to a FTP server. However information technology is designed to permit tracking progress of the upload:
-
- The uploadFile() method just initiates a file transfer session with the server (opening an output stream).
- The writeFileBytes() method will be invoked by the UploadTask to transfer a byte array to the server. This helps the UploadTaskdetermines upload progress and update the progress bar accordingly.
two. Lawmaking of UploadTask class
package net.codejava.swing.upload.ftp; import coffee.io.File; import java.io.FileInputStream; import javax.swing.JOptionPane; import javax.swing.SwingWorker; /** * Executes the file upload in a background thread and updates progress to * listeners that implement the coffee.beans.PropertyChangeListener interface. * @author www.codejava.net * */ public course UploadTask extends SwingWorker<Void, Void> { private static last int BUFFER_SIZE = 4096; private Cord host; private int port; individual Cord username; individual String password; individual String destDir; individual File uploadFile; public UploadTask(String host, int port, String username, String password, Cord destDir, File uploadFile) { this.host = host; this.port = port; this.username = username; this.password = password; this.destDir = destDir; this.uploadFile = uploadFile; } /** * Executed in background thread */ @Override protected Void doInBackground() throws Exception { FTPUtility util = new FTPUtility(host, port, username, password); try { util.connect(); util.uploadFile(uploadFile, destDir); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; long totalBytesRead = 0; int percentCompleted = 0; long fileSize = uploadFile.length(); while ((bytesRead = inputStream.read(buffer)) != -i) { util.writeFileBytes(buffer, 0, bytesRead); totalBytesRead += bytesRead; percentCompleted = (int) (totalBytesRead * 100 / fileSize); setProgress(percentCompleted); } inputStream.close(); util.finish(); } take hold of (FTPException ex) { JOptionPane.showMessageDialog(zippo, "Error uploading file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); setProgress(0); cancel(true); } finally { util.disconnect(); } return null; } /** * Executed in Swing's issue dispatching thread */ @Override protected void done() { if (!isCancelled()) { JOptionPane.showMessageDialog(null, "File has been uploaded successfully!", "Message", JOptionPane.INFORMATION_MESSAGE); } } }
Past extending the javax.swing.SwingWorker class, the UploadTask executes the file upload in a background thread (code in doInBackground() method) in order to prevent the GUI from freezing (so the GUI tin can update the progress bar's state). It notifies listeners about the upload progress by calling the setProgress() method each time a byte array has been transferred. Finally the done() method is invoked when the upload is done, to display a bulletin to the user.
iii. Code of SwingFileUploadFTP course
bundle cyberspace.codejava.swing.upload.ftp; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import coffee.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; import internet.codejava.swing.JFilePicker; /** * A Swing application that uploads files to a FTP server. * @author world wide web.codejava.net * */ public class SwingFileUploadFTP extends JFrame implements PropertyChangeListener { individual JLabel labelHost = new JLabel("Host:"); private JLabel labelPort = new JLabel("Port:"); private JLabel labelUsername = new JLabel("Username:"); individual JLabel labelPassword = new JLabel("Password:"); private JLabel labelUploadPath = new JLabel("Upload path:"); private JTextField fieldHost = new JTextField(40); individual JTextField fieldPort = new JTextField(5); private JTextField fieldUsername = new JTextField(30); private JPasswordField fieldPassword = new JPasswordField(30); private JTextField fieldUploadPath = new JTextField(30); individual JFilePicker filePicker = new JFilePicker("Choose a file: ", "Browse"); private JButton buttonUpload = new JButton("Upload"); individual JLabel labelProgress = new JLabel("Progress:"); private JProgressBar progressBar = new JProgressBar(0, 100); public SwingFileUploadFTP() { super("Swing File Upload to FTP server"); // set up up layout setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(5, 5, 5, 5); // set up components filePicker.setMode(JFilePicker.MODE_OPEN); buttonUpload.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent effect) { buttonUploadActionPerformed(result); } }); progressBar.setPreferredSize(new Dimension(200, 30)); progressBar.setStringPainted(true); // add together components to the frame constraints.gridx = 0; constraints.gridy = 0; add(labelHost, constraints); constraints.gridx = one; constraints.fill up = GridBagConstraints.HORIZONTAL; constraints.weightx = 1.0; add(fieldHost, constraints); constraints.gridx = 0; constraints.gridy = one; add(labelPort, constraints); constraints.gridx = one; add(fieldPort, constraints); constraints.gridx = 0; constraints.gridy = 2; add together(labelUsername, constraints); constraints.gridx = 1; add(fieldUsername, constraints); constraints.gridx = 0; constraints.gridy = 3; add(labelPassword, constraints); constraints.gridx = one; add together(fieldPassword, constraints); constraints.gridx = 0; constraints.gridy = 4; add together(labelUploadPath, constraints); constraints.gridx = 1; add(fieldUploadPath, constraints); constraints.gridx = 0; constraints.gridwidth = 2; constraints.gridy = v; constraints.anchor = GridBagConstraints.WEST; add(filePicker, constraints); constraints.gridx = 0; constraints.gridy = 6; constraints.anchor = GridBagConstraints.Centre; constraints.fill = GridBagConstraints.NONE; add together(buttonUpload, constraints); constraints.gridx = 0; constraints.gridy = seven; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.Due west; add(labelProgress, constraints); constraints.gridx = 1; constraints.fill = GridBagConstraints.HORIZONTAL; add together(progressBar, constraints); pack(); setLocationRelativeTo(nil); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /** * handle click event of the Upload button */ private void buttonUploadActionPerformed(ActionEvent event) { String host = fieldHost.getText(); int port = Integer.parseInt(fieldPort.getText()); String username = fieldUsername.getText(); String password = new String(fieldPassword.getPassword()); String uploadPath = fieldUploadPath.getText(); String filePath = filePicker.getSelectedFilePath(); File uploadFile = new File(filePath); progressBar.setValue(0); UploadTask task = new UploadTask(host, port, username, password, uploadPath, uploadFile); job.addPropertyChangeListener(this); task.execute(); } /** * Update the progress bar's state whenever the progress of upload changes. */ @Override public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); progressBar.setValue(progress); } } /** * Launch the application */ public static void master(String[] args) { try { // set look and feel to system dependent UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { ex.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new SwingFileUploadFTP().setVisible(true); } }); } }
This class constructs the user interface and is the main form of the awarding. Information technology displays a grade which allows the user to enter FTP server information (host proper name, port number, username and password) and upload information (upload path and the file to be uploaded). When the Upload button is clicked, an UploadTask object is created to execute the file upload.
It implements the method propertyChange() from the interface java.beans.PropertyChangeListener in order to be notified about the upload progress, and updates the progress bar's state accordingly.
For simplicity, the form's fields are non validated when the Upload push is clicked. So you should add validation code yourself.
four. Code of FTPException class
package net.codejava.swing.upload.ftp; public class FTPException extends Exception { public FTPException(Cord message) { super(message); } }
5. Testing the awarding
Run the application and enter the following information:
-
- Host: host name or IP accost of the FTP server.
- Port: port number (default is 21 for FTP).
- Username: name of the FTP account on the server.
- Password: password of the business relationship.
- Upload path: Path of the directory on the server where the file will be stored.
- Choose file: click Browse button to selection up a file to be uploaded.
Click Upload push button to start uploading the file. The progress bar is updated continuously during the file transfer:
When the upload completes, a message dialog appears:
If the username/password is incorrect, an error message dialog appears similar this:
Or if the upload path does not exist on the server:
Download source code and executable jar file of this application in the attachments department.
Related Tutorials:
- Java FTP File Upload Tutorial
- How to create File picker component in Swing
- Swing awarding to upload files to HTTP server with progress bar
- Coffee File Upload Servlet Case
Other Java Coding Tutorials:
- 10 Common Mistakes Every Beginner Java Programmer Makes
- 10 Java Core Best Practices Every Coffee Developer Should Know
- How to become a good programmer? 13 tasks you should exercise now
- How to calculate MD5 and SHA hash values in Java
- How to generate random numbers in Java
- Java File Encryption and Decryption Example
About the Writer:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Brand friend with him on Facebook and watch his Java videos yous YouTube.
Add comment
How To Create A Progress Popup For My Ftp Upload Java,
Source: https://www.codejava.net/coding/swing-application-to-upload-files-to-ftp-server-with-progress-bar
Posted by: smithhakis1990.blogspot.com
0 Response to "How To Create A Progress Popup For My Ftp Upload Java"
Post a Comment