FILE_URI path for Camera not working on IONIC 4

Viewed 8273

When using the Cameara to take a picture with destinationType: this.camera.DestinationType.FILE_URI, the resulting URL will not work to display the image. For example, when attempting to take a photo like this:

this.camera.getPicture(options).then((url) => {
        // Load Image
        this.imagePath = url;
    }, (err) => {
        console.log(err);
    });

Attempting to display it as <img [src]="imagePath" > will result in an error (file not found).

The problem here is that the URL is in the file:///storage... path instead of the correct one based on localhost.

4 Answers

In previous versions of Ionic, this would be solved by using normalizeURL. This will not work on Ionic 4 (or at least I could not make it work).

To solve this issue, you will need to use convertFileSrc():

import {WebView} from '@ionic-native/ionic-webview/ngx';
...
this.camera.getPicture(options).then((url) => {
        // Load Image
        this.imagePath = this.webview.convertFileSrc(url);
    }, (err) => {
        console.log(err);
    });

Now the image URL will be in the appropriate http://localhost:8080/_file_/storage... format and will load correctly.

See WKWebView - Ionic Docs for more information.

In my case, the following code works with me

const downloadFileURL = 'file:///...';

// Convert a `file://` URL to a URL that is compatible with the local web server in the Web View plugin.
const displayedImg = (<any>window).Ionic.WebView.convertFileSrc(downloadFileURL);

UPDATE december 2021:

You have to install the new Ionic Webview

RUN:

ionic cordova plugin add cordova-plugin-ionic-webview

npm install @awesome-cordova-plugins/ionic-webview

Import it in app.module and your page where you wanna use it:

import { WebView } from '@awesome-cordova-plugins/ionic-webview/ngx'; 
image = "";
constructor(private webview: WebView){}

Then this will work:

this.camera.getPicture(options).then((imageData) => {
 this.image = this.webview.convertFileSrc(imageData)
}, (err) => {
 // Handle error
});

And show it in the HTML page:

    <img [src]="image" alt="">
Related