一、ant方式
在module级下的build.gradle中添加以下代码
android {
configurations {
ftpAntTask
}
}
dependencies {
api fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
//添加antlibs依赖,用于ftp上传
ftpAntTask("org.apache.ant:ant-commons-net:1.10.14") {
module("commons-net:commons-net:3.8.0")
}
}
//上传任务
task uploadReleaseToFtp{
group('aar')
def localFile = "$project.projectDir" + "/" +openReleaseDir + MicroClientZip
def file = new File(localFile)
if (!file.exists()) {
return
}
ant {
// 定义 FTP 任务
taskdef(name: 'ftp',
classname: 'org.apache.tools.ant.taskdefs.optional.net.FTP',
classpath: configurations.ftpAntTask.asPath)
def ftpUrl = '1.1.1.1'
def ftpPort = '2121'
def username = '用户名'
def password = '密码'
def remoteDir = "/outputs/"
ftp(server: ftpUrl,
port: ftpPort,
userid: username,
password: password,
remoteDir: remoteDir,
passive: "yes",
binary: "yes",
verbose: "yes"
) {
fileset(dir: localFile)
}
}
doLast {
//上传完删除本地文件
file.delete()
}
}
二、FTPClient方式
1、在项目级build.gradle中添加依赖
dependencies {
classpath 'com.android.tools.build:gradle:3.4.3'
//添加以下依赖
classpath 'commons-net:commons-net:3.8.0'
}
2、在module级build.gradle中添加
task uploadReleaseToFtp(){
group('aar')
def localZipName = "${project.getName()}.zip"
def localZipFilePath = "$project.projectDir" + "/" +openReleaseDir + localZipName
def localZipFile = new File(localZipFilePath)
if (!localZipFile.exists()) {
println "============== localZipFile 不存在"
return
}
ant {
def ftpServer = "1.1.1.1"
def ftpUsername = '用户名'
def ftpPassword = '密码'
def remoteFile = "/client/outputs/cloudgame/gdt/" + localZipName
// 创建 FTP 客户端对象
def ftpClient = new FTPClient()
try {
// 连接到 FTP 服务器
ftpClient.connect(ftpServer, 2121)
ftpClient.login(ftpUsername, ftpPassword)
// 切换到指定远程目录
//ftpClient.changeWorkingDirectory(remoteDirectory)
ftpClient.setControlEncoding("UTF-8")
// 设置文件类型为二进制
ftpClient.setFileType(FTP.BINARY_FILE_TYPE)
ftpClient.enterLocalPassiveMode()
// 上传文件
def inputStream = new FileInputStream(localFile)
// 上传文件到远程路径
boolean success = ftpClient.storeFile(remoteFile, inputStream)
if (success){
println "============== File uploaded successfully."
}else {
println "============== File upload failed. Reply code: " + ftpClient.getReplyCode()
}
} finally {
inputStream.close()
// 关闭 FTP 连接
if (ftpClient.isConnected()) {
ftpClient.logout()
ftpClient.disconnect()
}
}
}
doLast {
localZipFile.delete()
}
}