以下是一个简单的Java代码实现上传文件到FTP服务器的案例,需要借助Apache Commons Net库来实现FTP文件上传功能。
import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FTPUploader { private static final String FTP_HOST = "ftp.example.com"; // FTP服务器地址 private static final String FTP_USER = "username"; // FTP用户名 private static final String FTP_PASS = "password"; // FTP密码 private static final int FTP_PORT = 21; // FTP端口号 public static void uploadFile(File file, String remoteDir) throws IOException { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(FTP_HOST, FTP_PORT); ftpClient.login(FTP_USER, FTP_PASS); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); boolean success = ftpClient.changeWorkingDirectory(remoteDir); if (!success) { throw new IOException("无法切换到远程目录: " + remoteDir); } String fileName = file.getName(); FileInputStream inputStream = new FileInputStream(file); System.out.println("开始上传文件: " + fileName); boolean uploaded = ftpClient.storeFile(fileName, inputStream); inputStream.close(); if (uploaded) { System.out.println("成功上传文件: " + fileName); } else { System.out.println("上传文件失败: " + fileName); } } finally { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } } public static void main(String[] args) { File file = new File("D:\\test.txt"); // 待上传的文件路径 String remoteDir = "/uploads/"; // 远程目录 try { uploadFile(file, remoteDir); } catch (IOException ex) { ex.printStackTrace(); } } }
该代码使用Apache Commons Net库实现FTP文件上传功能,先连接FTP服务器,然后切换到指定的远程目录,最后上传文件到FTP服务器。需要注意的是,FTP用户名和密码是关键,需要保证其安全性,防止泄露导致FTP服务器被攻击。同时,还需要考虑文件上传的稳定性和安全性等因素,以保证文件上传的正常和安全。
评论