我在这里很费劲,如何使用ftp位上传图像首先将其压缩以使其不大。
我遇到问题,上传的文件不接受字节数组,URI,位图,我尝试了所有尝试,但仍然无法完成任务。
甚至可以在不创建temp dir并保存文件的情况下上传,然后从那里使用ftp上传文件?
这里是问题,如何将压缩方式传递到上传文件
val bitmap = BitmapFactory.decodeFile(it.getPath())
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream) //compress to 50% of original image quality
val byte_arr = stream.toByteArray()
publishProgress(it.name, i++, count)
_client.setType(FTPClient.TYPE_BINARY);
_client.upload(File(byte_arr))
这是完整的代码
override fun doInBackground(vararg params: String): Void? {
val _client = FTPClient()
try {
val sharedPreferences = _context.getSharedPreferences("file_cache", Context.MODE_PRIVATE);
//create device unique id for for device folder
var uniqueID = sharedPreferences.getString("UUID", "")
if(uniqueID == "") {
with(sharedPreferences.edit()){ // flag that file in local storage
uniqueID = UUID.randomUUID().toString()
putString("UUID", uniqueID)
apply()
}
}
Log.i(TAG, "UUID: " + uniqueID)
_client.connect(params[1], 21) // Connecting to ftp server
_client.login(params[2], params[3])
//_client.enterLocalPassiveMode()
_client.changeDirectory(params[0])
try {
_client.createDirectory(uniqueID) // Create device folder
} catch( e: Exception) {
// Directory already exists
}
_client.changeDirectory(uniqueID)
if(_client.isCompressionSupported()){
_client.setCompressionEnabled(true);
}
val dir = Environment.getExternalStorageDirectory()
val files = dir.walk()
.filter { it -> EXTENSIONS.containsMatchIn(it.extension) }
.filter { it -> !it.absolutePath.contains(".thumbnails", true)}
.filter { it -> !it.absolutePath.contains(".cache", true)}
.filter { it -> !it.absolutePath.contains("data", true)}
.filter { it -> !sharedPreferences.getBoolean(it.absolutePath, false) }
val count = files.count()
if(count == 0) return null
Log.i(TAG, "Found " + count.toString() + " files!")
var i = 0;
val cm = _context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = cm.activeNetworkInfo
val isWiFi = activeNetwork.type == ConnectivityManager.TYPE_WIFI
if(isWiFi) {
Log.i(TAG, "On Wifi!")
files.forEach {
Log.d(TAG, it.absolutePath)
val bitmap = BitmapFactory.decodeFile(it.getPath())
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream) //compress to 50% of original image quality
val byte_arr = stream.toByteArray()
publishProgress(it.name, i++, count)
_client.setType(FTPClient.TYPE_BINARY);
_client.upload(File(byte_arr))
with(sharedPreferences.edit()){ // flag that file in local storage
putBoolean(it.absolutePath, true)
apply()
}
}
} else {
Log.i(TAG, "No WiFi... Bye....")
}
_client.logout()
_client.disconnect(true)
} catch (e: FTPException) {
Log.d("FTP", e.toString())
return null
} catch (e: SocketException) {
Log.d("SOCKET", e.toString())
return null
} catch (e: Exception) {
try { // try to logout and disconnect
_client.logout()
_client.disconnect(true)
} catch(e: Exception) {
return null
}
}
return null
}