I strugle a lot here, how to upload images with ftp bit first compress it so it's not that big.
I got problem the upload don't accept bytearray, URI, bitmap, i try everything but i still fail to accomplish the task.
Are even possible to upload without making temp dir and saving file there then from there upload it using ftp?
Here is the issue, how to pass that compression to the upload
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))
And here is the full code
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
}
Related
I'm writing unit tests for a use case that basically creates a file with the contents of an InputStream.
However, with the lines:
val path = context.filesDir.path + "/issues.csv"
val fos = FileOutputStream(path)
I'm having trouble, as the when trying to create the FileOutputStream from the path it always results in a FileNotFoundException.
This is the complete code:
class SaveFileUseCase #Inject constructor(
private val context: Context,
#DefaultCoroutineDispatcher private val defaultCoroutineDispatcher: CoroutineDispatcher
) {
suspend operator fun invoke(body: ResponseBody) =
withContext(defaultCoroutineDispatcher) {
saveFile(body)
}
private fun saveFile(body: ResponseBody?) {
if (body == null) {
return
}
var input: InputStream? = null
try {
input = body.byteStream()
val path = context.filesDir.path + "/issues.csv"
val fos = FileOutputStream(path)
fos.use { output ->
val buffer = ByteArray(4 * 1024) // or other buffer size
var read: Int
while (input.read(buffer).also { read = it } != -1) {
output.write(buffer, 0, read)
}
output.flush()
}
} catch (e: Exception) {
Log.e("Error saving file", e.toString())
} finally {
input?.close()
}
}
}
How can I test this?
Thanks a lot in advance!
I'm allowing user to create an image. When they click "create", i save the image on screen to a bitmap and then save the content URI (content://com.android.providers.media.documents/document/image%3A1000003643) returned to local storage so i can read from it later to display the image. I believe this only grants me temporary access as i get the below error after a short while when trying to display the image in another section of the app
D/AsyncImageError: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord (pid=20027, uid=10663) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
Does anyone know the best way to save an image and then access it indefinitely whenever I want?
save bitmap local storage.
try {
val bitmapDims = ImageUtils.getBitmapDims(BackgroundRemoverActivity.selectedImageUri, this#SmoothActivity
)
val i = bitmapDims.outWidth
var i2 = bitmapDims.outHeight
val smoothActivity = this#SmoothActivity
if (i > i2) {
i2 = i
}
smoothActivity.saveBitmap(i2)
} catch (e: Exception) {
e.printStackTrace()
}
fun saveBitmap(i: Int) {
dimension = i
showDialog = false
val show = ProgressDialog.show(
this,
"",
getString(if (gotoShare) R.string.save_image_ else R.string.processing_image),
true
)
show.setCancelable(false)
Thread(Runnable {
val str: String
try {
// val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "/" + HelperClass.FOLDER_NAME)
val file = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/" + HelperClass.FOLDER_NAME
)
if (!file.exists()) {
if (!file.mkdirs()) {
Log.d("", "Can't create directory to save image.")
Toast.makeText(
this#SmoothActivity.applicationContext,
"Can't create directory to save image.",
1
).show()
return#Runnable
}
}
val sb = StringBuilder()
sb.append("Photo_")
sb.append(System.currentTimeMillis())
val sb2 = sb.toString()
str = if (inPNG) {
val sb3 = StringBuilder()
sb3.append(sb2)
sb3.append(".png")
sb3.toString()
} else {
val sb4 = StringBuilder()
sb4.append(sb2)
sb4.append(".jpg")
sb4.toString()
}
val smoothActivity = this#SmoothActivity
val sb5 = StringBuilder()
sb5.append(file.path)
sb5.append(File.separator)
sb5.append(str)
smoothActivity.filename = sb5.toString()
val file2 = File(filename)
if (inPNG) {
savePNGImage(file2, i)
show.dismiss()
} else {
saveJPGImage(file2, i)
show.dismiss()
}
Thread.sleep(1000)
show.dismiss()
} catch (e: Exception) {
e.printStackTrace()
}
}).start()
show.setOnDismissListener { dialogInterface: DialogInterface? ->
if (showDialog) {
if (gotoShare) {
val applicationContext = this#SmoothActivity.applicationContext
val sb = StringBuilder()
sb.append(this#SmoothActivity.getString(R.string.saved))
sb.append(" ")
sb.append(filename)
Toast.makeText(applicationContext, sb.toString(), Toast.LENGTH_SHORT).show()
val intent = Intent(this#SmoothActivity, ShareActivity::class.java)
intent.putExtra("path", filename)
intent.putExtra("showTbg", inPNG)
this#SmoothActivity.startActivity(intent)
HelperClass.showPopAdWithCount(this)
// HelperClass.showPopAd(SmoothActivity.this);
return#setOnDismissListener
/* onBackPressed()*/
}
val intent = Intent(this#SmoothActivity, BackgroundChangerActivity::class.java)
intent.putExtra("value", "2")
this#SmoothActivity.startActivity(intent)
Log.d("ttpscheckitem",filename.toString()+ "smooth");
/*onBackPressed()*/
} else if (gotoShare) {
val create = AlertDialog.Builder(
this#SmoothActivity,
if (VERSION.SDK_INT >= 14) 16974126 else 16973835
).setTitle(this#SmoothActivity.resources.getString(R.string.resolution_error_title))
.setMessage(this#SmoothActivity.resources.getString(R.string.rsolution_error_msg))
.setCancelable(false)
.setPositiveButton(this#SmoothActivity.resources.getString(R.string.ok)) { dialogInterface, i1 -> showResolutionOptDialog() }
.create()
create.window!!.attributes.windowAnimations = R.style.DialogAnimation_
create.show()
}
}
}
get local sorage image ;
final List loadAllImages = loadAllImages(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
this.cutoutAdapter = new CutoutAdapter(this, loadAllImages);
this.cutout_recyclerview.setAdapter(cutoutAdapter);
This is my following code.
I'm having a issue display image from Google Drive.
Source code from https://www.section.io/engineering-education/backup-services-with-google-drive-api-in-android/
I have also worked with this image url https://drive.google.com/uc?id=FILE_ID but only worked in anyone with the link access not restricted images.
fun downloadFileFromGDrive(id: String) {
getDriveService()?.let { googleDriveService ->
CoroutineScope(Dispatchers.IO).launch {
val gDriveFile = googleDriveService.Files().get(id).execute()
Log.e("gDriveFile", gDriveFile.toString())
val outputStream: OutputStream = ByteArrayOutputStream()
googleDriveService.files()[id].executeMediaAndDownloadTo(outputStream)
}
} ?: Toast.makeText(context, "Please Log In first!", LENGTH_SHORT).show()
}
Use the following function It will download Google drive Image and save it to the app private files folder.
fun downloadFileFromGDrive(id: String) {
getDriveService()?.let { googleDriveService ->
CoroutineScope(Dispatchers.IO).launch {
Log.e("idDownload", id)
val file = File(context.filesDir, "${id}.jpg")
if (!file.exists()) {
try {
val gDriveFile = googleDriveService.Files().get(id).execute()
saveImageInFilesDir(gDriveFile.id)
} catch (e: Exception) {
println("!!! Handle Exception $e")
}
}
}
} ?: ""
}
private fun saveImageInFilesDir(id: String?) {
getDriveService()?.let { googleDriveService ->
CoroutineScope(Dispatchers.IO).launch {
val file = File(context.filesDir, "${id}.jpg")
try {
val outputStream = FileOutputStream(file)
googleDriveService.files()[id]
.executeMediaAndDownloadTo(outputStream)
if (id != null) {
googleDriveService.readFile(id)
}
outputStream.flush()
outputStream.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
I want to load rtf files with webview using raw folder. Below is my code;
val urlWebView = findViewById<WebView>(R.id.webview)
readTextFromResource(R.raw.lettemp_369)?.let { urlWebView.loadData(it, "text/rtf", "utf-8") };
Below is function;
private fun readTextFromResource(resourceID: Int): String? {
val raw: InputStream = resources.openRawResource(resourceID)
val stream = ByteArrayOutputStream()
var i: Int
try {
i = raw.read()
while (i != -1) {
stream.write(i)
i = raw.read()
}
raw.close()
} catch (e: IOException) {
e.printStackTrace()
}
return stream.toString()
}
I want to load rtf files with webview using raw folder. Below is my code;
val urlWebView = findViewById<WebView>(R.id.webview)
readTextFromResource(R.raw.lettemp_369)?.let { urlWebView.loadData(it, "text/rtf", "utf-8") };
Below is function;
private fun readTextFromResource(resourceID: Int): String? {
val raw: InputStream = resources.openRawResource(resourceID)
val stream = ByteArrayOutputStream()
var i: Int
try {
i = raw.read()
while (i != -1) {
stream.write(i)
i = raw.read()
}
raw.close()
} catch (e: IOException) {
e.printStackTrace()
}
return stream.toString()
}