package com.gx.ftp; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class TestFtp { public static void main(String[] args) { String path = "D:/upLoadFiles/APTransferPlan/1a4f74a0-f6ac-4e91-8225-3dca5a7ccad1"; String filename = "02.jpg"; String name = null; try { name = new String(filename.getBytes("GBK"), "iso-8859-1"); // 处理上传到ftp上的文件名不能为中文的问题 FileInputStream in = new FileInputStream(new File(path)); boolean flag = uploadFile("127.0.0.1", 21, "test", "1","E:/ftptest", name, in); System.out.println(flag); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Description: 向FTP服务器上传文件 * @param url: FTP服务器hostname * @param port: FTP服务器端口 * @param username:FTP登录账号 * @param password: FTP登录密码 * @param path:FTP服务器保存目录 * @param filename:上传到FTP服务器上的文件名 * @param input: 输入流 * @return 成功返回true,否则返回false */ public static boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) { boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(url, port);// 连接FTP服务器 ftp.login(username, password);// 登录 reply = ftp.getReplyCode(); //处理上传到ftp的文件打不开,图片破损等问题 ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.setControlEncoding("GBK"); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } 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; } }
时间: 2024-12-12 16:54:08