ftp上传视频文件
代码
class FTPClientFunctions {
private var ftpClient: FTPClient? = null // FTP客户端
/**
* 连接到FTP服务器
*
* @param host ftp服务器域名
* @param username 访问用户名
* @param password 访问密码
* @param port 端口
* @return 是否连接成功
*/
fun ftpConnect(host: String, username: String, password: String, port: Int): Boolean {
try {
ftpClient = FTPClient()
Log.d(TAG, "connecting to the ftp server $host :$port")
ftpClient!!.connect(host, port)
// 根据返回的状态码,判断链接是否建立成功
if (FTPReply.isPositiveCompletion(ftpClient!!.replyCode)) {
Log.d(TAG, "login to the ftp server")
val status = ftpClient!!.login(username, password)
/*
* 设置文件传输模式
* 避免一些可能会出现的问题,在这里必须要设定文件的传输格式。
* 在这里我们使用BINARY_FILE_TYPE来传输文本、图像和压缩文件。
*/
ftpClient!!.setFileType(FTP.BINARY_FILE_TYPE)
ftpClient!!.enterLocalPassiveMode()
return status
}
} catch (e: Exception) {
e.printStackTrace()
Log.d(TAG, "Error: could not connect to host $host")
}
return false
}
/**
* 断开ftp服务器连接
*
* @return 断开结果
*/
fun ftpDisconnect(): Boolean {
// 判断空指针
if (ftpClient == null) {
return true
}
// 断开ftp服务器连接
try {
ftpClient!!.logout()
ftpClient!!.disconnect()
return true
} catch (e: Exception) {
Log.d(TAG, "Error occurred while disconnecting from ftp server.")
}
return false
}
/**
* ftp 文件上传
*
* @param srcFilePath 源文件目录
* @param desFileName 文件名称
* @param desDirectory 目标文件
* @return 文件上传结果
*/
fun ftpUpload(srcFilePath: String, desFileName: String, desDirectory: String): Boolean {
var status = false
try {
val srcFileStream = FileInputStream(srcFilePath)
status = ftpClient!!.storeFile(desFileName, srcFileStream)
srcFileStream.close()
Log.d(TAG, "=视频上传成功=" )
return status
} catch (e: Exception) {
e.printStackTrace()
Log.d(TAG, "upload failed: " + e.localizedMessage)
}
return status
}
/**
* ftp 更改目录
*
* @param path 更改的路径
* @return 更改是否成功
*/
fun ftpChangeDir(path: String): Boolean {
var status = false
try {
status = ftpClient!!.changeWorkingDirectory(path)
} catch (e: Exception) {
e.printStackTrace()
Log.d(TAG, "change directory failed: " + e.localizedMessage)
}
return status
}
companion object {
private val TAG = "FTPClientFunctions"
}
}