How to display a camera image in an img tag with Cordova when using wkwebview

1.1k Views Asked by At

The app uses cordova-ios version 6.0.0. So all WkWebView code.

When the user selects an image using the cordova-plugin-camera plugin, and I set the returned image URI as the src attribute of an img tag, this triggers an error, because the URI begins with file://:

Not allowed to load local resource: file:///xxx/xxx/xxx/xxx.jpg

How is this done with wkwebview and in cordova-ios version 6, to display the selected image?

I have tried countless things and cannot make this work. I am using WkURLSchemeHandler, I set the preferences in the config.xml to be app and localhost as suggested here:

<preference name="scheme" value="app" />
<preference name="hostname" value="localhost" />

I see that the file:// URL returned by the camera plugin is stored in the tmp folder. So I tried accessing it with app://localhost, but I get 404 error:

var pos = photoURI.indexOf('/tmp');
if(pos >=0){
    photoURI = 'app://localhost' + photoURI.substr(pos);
}
1

There are 1 best solutions below

0
On

app://localhost only serves www assets.

Solution 1:

Use this plugin https://github.com/communico/cordova-httpd to start a local server inside app

cordova.plugins.CorHttpd.startServer({
    'www_root': cordova.file.dataDirectory.replace( 'file://', '' ),
    'port': 8080,
    'localhost_only': false
}, function( url ){
    // eg. http://10.0.0.185:8080/
    // if localhost_only is true,then url is http://127.0.0.1:8080/
    console.log(url);
}, function( error ){
    console.log(error);
});

For example, if a file path looks like: file:///data/user/0/com.pushsoft.aio5app/files/image/7c8f2985-01b3-4fd2-ad7b-f39812a920a2

you can use this url to show the image: http://127.0.0.1:8080/image/7c8f2985-01b3-4fd2-ad7b-f39812a920a2

Solution 2:

You can put images in file:///var/mobile/Containers/Data/Application/<UUID>/tmp/,<img> can only display images inside this directory via 'file://' protocal