gradle脚本上传文件到ftp

一、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.8.4") {
        module("commons-net:commons-net:3.8.0")    {
            dependencies "oro:oro:2.0.8:jar"
        }
    }
}


task uploadReleaseToFtp{
    group('aar')
    ant {
        // 定义 FTP 任务
        taskdef(name: 'ftp',
                classname: 'org.apache.tools.ant.taskdefs.optional.net.FTP',
                classpath:  configurations.ftpAntTask.asPath)

        def ftpUrl = '10.7.2.10'
        def ftpPort = '2121'
        def username = '用户名'
        def password = '密码'
        def remoteDir = '/upload/xxx/yyy'
        ftp(server: ftpUrl,
                port: ftpPort,
                userid: username,
                password: password,
                remoteDir: remoteDir,
                passive: "yes",
                binary: "yes"
        ) {
            fileset(dir: openReleaseDir) {
                include(name: "*.zip")
            }
        }
    }
}

二、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 modulePath = project.projectDir
    def localFile = "$modulePath/open/release"
    def file = new File(localFile)
    if (!file.exists()) {
        return
    }

    ant {
        def ftpServer = "10.73.22.100"
        def ftpUsername = '用户名'
        def ftpPassword = '密码'
        def remoteDirectory = "/client/outputs/"
        def remoteFile = "test.zip"

        // 创建 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(remoteDirectory + 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 {
        file.delete()
    }
}

你可能感兴趣的:(python,开发语言)