1、添加依赖库
创新互联总部坐落于成都市区,致力网站建设服务有网站设计、网站制作、网络营销策划、网页设计、网站维护、公众号搭建、成都微信小程序、软件开发等为企业提供一整套的信息化建设解决方案。创造真正意义上的网站建设,为互联网品牌在互动行销领域创造价值而不懈努力!
在项目的build.gradle文件中添加以下依赖库:
dependencies { implementation 'org.apache.commons:commonsnet:3.8.0' }
2、创建FTPClient类
import org.apache.commons.net.ftp.FTPClient; import java.io.FileInputStream; import java.io.IOException; public class FTPClientUtil { private String host; private int port; private String username; private String password; private FTPClient ftpClient; public FTPClientUtil(String host, int port, String username, String password) { this.host = host; this.port = port; this.username = username; this.password = password; ftpClient = new FTPClient(); } public boolean connect() { try { ftpClient.connect(host, port); ftpClient.login(username, password); return true; } catch (IOException e) { e.printStackTrace(); return false; } } public boolean uploadFile(String remotePath, String fileName) { try (FileInputStream inputStream = new FileInputStream(fileName)) { boolean result = ftpClient.storeFile(remotePath + "/" + fileName, inputStream); inputStream.close(); return result; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } }
3、使用FTPClientUtil上传文件到FTP服务器
public class MainActivity extends AppCompatActivity { private static final String HOST = "your_ftp_server_host"; private static final int PORT = 21; // 默认FTP端口号为21 private static final String USERNAME = "your_ftp_server_username"; private static final String PASSWORD = "your_ftp_server_password"; private static final String REMOTE_PATH = "/upload/"; // 远程服务器上的文件路径,根据实际情况修改 private static final String LOCAL_FILE_PATH = "/storage/emulated/0/Download/test.txt"; // 本地文件路径,根据实际情况修改 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FTPClientUtil ftpClientUtil = new FTPClientUtil(HOST, PORT, USERNAME, PASSWORD); if (ftpClientUtil.connect()) { boolean result = ftpClientUtil.uploadFile(REMOTE_PATH, LOCAL_FILE_PATH); if (result) { Toast.makeText(this, "文件上传成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "文件上传失败", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, "连接FTP服务器失败", Toast.LENGTH_SHORT).show(); } } }
1、安装FTP客户端软件(如FileZilla)并配置好服务器信息,确保服务器地址、端口、用户名和密码等信息正确。
当前标题:android上传文件到ftp服务器_本地Linux主机使用FTP上传文件到Linux云服务器
链接URL:http://www.shufengxianlan.com/qtweb/news49/526749.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联