Use Java to implement ftp file upload. I'm using commons-net-1.4.1.zip. It contains many Java network programming toolkits.
1. Load the commons-net-1.4.1.jar package into the project.
2. Look at the following code:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FileTool { /** * Description: Upload file to the FTP server* @Version 1.0 * @param url FTP server hostname * @param port FTP server port* @param username FTP login account* @param password FTP login password* @param path FTP server save directory* @param filename Uploaded to the FTP server* @param input Input stream* @return Return true successfully, otherwise false * */ public static boolean uploadFile(String url,// FTP server hostname int port,// FTP server port String username, // FTP login account String password, // FTP login password String path, // FTP server save directory String filename, // File name uploaded to the FTP server InputStream input // Input stream){ boolean success = false; FTPClient ftp = new FTPClient(); ftp.setControlEncoding("GBK"); try { int reply; ftp.connect(url, port);// Connect to the FTP server// If the default port is used, you can directly connect to the FTP server by using ftp.connect(url); ftp.login(username, password);// Log in reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.setFileType(FTPClient.BINARY_FILE_TYPE); ftp.makeDirectory(path); ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } return success; } /** * Upload local files to the FTP server* */ public static void upLoadFromProduction(String url,// FTP server hostname int port,// FTP server port String username, // FTP login account String password, // FTP login password String path, // FTP server save directory String filename, // Upload to the FTP server filename String orginfilename // Enter stream filename) { try { FileInputStream in = new FileInputStream(new File(orginfilename)); boolean flag = uploadFile(url, port, username, password, path,filename, in); System.out.println(flag); } catch (Exception e) { e.printStackTrace(); } } //Test public static void main(String[] args) { upLoadFromProduction("192.168.13.32", 21, "hanshibo", "han", "Han Shibo Test", "hanshibo.doc", "E:/temp/H2 database usage.doc"); } } 3. Run directly. You can upload the specified file to the ftp server. If you need a jar package, you can download it in my resources.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.