-1

I have been able to get the content:// Uri of the image from the gallery. I have to show the preview of the image and upload it onto the server as well. A file can not be created with content:// Uri.

So what is the standard way of picking up image and uploading it to server in Android 10 and above with scoped storage in place.

Edit It's an image file and I have to reduce its size before uploading it to the server. Even size reduce function is failing as its unable to locate the file.

Piyush
  • 163
  • 1
  • 10
  • The same as allways. Use the obtained uri for the preview and to upload to server. – blackapps Feb 22 '21 at 19:50
  • @blackapps file which needs to be uploaded, can't be created with content:// uri – Piyush Feb 22 '21 at 19:56
  • You do not have to create that file. The file exists already otherwise you could not have picked it from the gallery and obtained an uri to it. – blackapps Feb 22 '21 at 20:01
  • The options for uploading will depend on what library that you are using for that uploading. If you are using OkHttp, there are [existing recipes for uploading via a `content` `Uri`](https://stackoverflow.com/a/56308643/115145). – CommonsWare Feb 22 '21 at 20:57
  • @blackapps I am not trying to create a new file...I am trying to create file object from content:// uri...which is failing with error "uri scheme is not file". – Piyush Feb 23 '21 at 05:16
  • @CommonWare I am using retrofit – Piyush Feb 23 '21 at 05:17
  • @RyanM....solution given in the link didnt work – Piyush Feb 23 '21 at 05:17
  • You do not need a File object either to upload a file from uri. – blackapps Feb 23 '21 at 07:41
  • @blackapps as image size needs to be reduced, so can't do operation on the same uri returned from gallery. For that purpose, a temp file is created reduced its size and uploaded onto server – Piyush Feb 23 '21 at 10:03

1 Answers1

0

Created a temp file and coppied uri's inputstream into the temp file

private val galleryLauncher =
        registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
            if (uri != null) {
                val tempFile = File.createTempFile("TempFile", ".jpg", externalCacheDir)
                val inputStream: InputStream? = contentResolver.openInputStream(uri)
                if(inputStream != null) {
                    FileOutputStream(tempFile , false).use { outputStream ->
                    var read: Int
                    val bytes = ByteArray(DEFAULT_BUFFER_SIZE)
                    while (inputStream.read(bytes).also { read = it } != -1) {
                    outputStream.write(bytes, 0, read)
                }
                outputStream.close()
            }
            inputStream.close()
                    
            //saved the tempfile's path for future reference        
                }
            }
        }

Preview of the image, compress the image size and upload the image will now happen through temp file's path.

Piyush
  • 163
  • 1
  • 10