简体   繁体   中英

How to upload file from downloads folder in Android Oreo and above?

I am trying to write the code to upload file from Android Oreo and Above. First I am running a intent to get the uri of the file.

intent_upload.action = Intent.ACTION_GET_CONTENT
return Intent.createChooser(intent_upload, pickerTitle)

But when I select file from downloads folder, it returns a null filepath from following code. It works perfectly for devices below Android Oreo but I cannot find any solution for android o and above.

Please help

val id = DocumentsContract.getDocumentId(uri)
val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id));
return getDataColumn(context, contentUri, null, null)

Code for getDataColumn is as follow

fun getDataColumn(context: Context, uri: Uri?, selection: String?,
                          selectionArgs: Array<String>?): String? {

        var cursor: Cursor? = null
        val column = "_data"
        val projection = arrayOf(column)

        try {
            cursor = context.contentResolver.query(uri!!, projection, selection, selectionArgs, null)
            val temp = context
            if (cursor != null && cursor.moveToFirst()) {
                val index = cursor.getColumnIndexOrThrow(column)
                return cursor.getString(index)
            }
        }catch (e:Exception){

        } finally {
            cursor?.close()
        }
        return null
    }

It is happening for API 26 and above.

My motive is to upload a pdf file from the downloads folder in Android.

I know this is past due. I also faced this issue and I was able to find a solution from this gist. FileUtils.java . Just use this util class in your project

Just leaving this here for people who face this issue in the future. Wasted a couple of hours working on this.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Uri uri = data.getData();
    File originalFile = new File(FileUtils.getRealPath(this,uri));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM