How to access external storage from WebView's HTML page?

Viewed 364

I'm writing an application with a WebView frontend. I'd like to allow users to take pictures and then display them embedded into HTML.

So far I managed to implement taking pictures and storing them in the external storage, but I cant figure out how to access them from HTML, e.g. via the <img/> tag.

Steps I did already:

  1. Created an externally stored file:

    private fun createImageFile(): File {
        val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val file = File(storageDir, "pic.jpg")
        file.createNewFile()
        return file
    }
    
  2. Added necessary permission declarations in manifest:

     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    
  3. Since those are dangerous permissions, I made sure they're granted at runtime (omitting code because I've double checked it works).

  4. Exposed the file uri via @JavascriptInterface to my HTML page:

     @JavascriptInterface
     fun getSelfiePath() : String {
          return file.toURI().toString()
     }
    
  5. I referenced the uri from my <img/> tag:

     function populatePicture() {
         let picDiv = document.getElementById("pic")
         picDiv.innerHTML = '<img src="' + controller.getPicturePath() + '" />'
         // getPicturePath() returns path in the format of: 
         // /storage/emulated/0/Android/data/{package}/files/Pictures/pic.jpg
     }
    

I realize all of this is not what you'd call a minimal working example but I found it really hard to provide one, since the problems spans over many "domains".

I've tried many different approaches with the URI, such as prepending it with file:///, for instance, but none of it worked. What's confusing me even more, is that I cant easily access compile-time resources this way, but for one placed in external storage, it simply does not work.

What is the correct approach? I feel like I'm missing something when it comes to:

  1. Accessing external storage from HTML.

or

  1. Correct use of methods to generate the URI string.
0 Answers
Related