17

I am using ionic 3 android build apk and trying to laod image from file:///storage/emulated/0/data/io.ionic.vdeovalet/cache/image.jpeg




    takePicture(sourceType) {
        try {
    // Create options for the Camera Dialog
          var options = {
            quality: 100,
            destinationType: this.camera.DestinationType.FILE_URI,
            encodingType: this.camera.EncodingType.JPEG,
            sourceType: sourceType,
          };
          this.camera.getPicture(options).then((imagePath) => {
    // Special handling for Android library
            if (this.platform.is('android') && sourceType ===
              this.camera.PictureSourceType.PHOTOLIBRARY) {
              this.filePath.resolveNativePath(imagePath)
                .then(filePath => {
                  let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
                  let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1,
                    imagePath.lastIndexOf('?'));
                  this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
                  this.lastImage = filePath;
                });
            } else {
              var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
              var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
              this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
            }
          }, (err) => {
            this.presentToast('Error while selecting image.');
          });


        } catch (e) {
          console.error(e);
        }


      }

Error: Not allowed to load local resource
android 6.0.1

Muneeb Khan
  • 169
  • 1
  • 1
  • 5

9 Answers9

34

No Need To Downgrade just write this code.

private win: any = window;
    this.win.Ionic.WebView.convertFileSrc(path);
kunal shaktawat
  • 1,428
  • 12
  • 21
17

I had the same issues and it turns out that The new ionic webview plugin is the cause for the problem.

The new plugin: cordova-plugin-ionic-webview @ 2.x seem unstable...

to get it working downgraded back to cordova-plugin-ionic-webview@1.2.1 and all should work

Steps:

1. uninstall webview

ionic cordova plugins rm cordova-plugin-ionic-webview

2. install old one:

ionic cordova plugins add cordova-plugin-ionic-webview@1.2.1

3. clean cordova

cordova clean android
aphoe
  • 2,586
  • 1
  • 27
  • 31
Awesome Jim
  • 378
  • 3
  • 7
  • This is the same thing I ran into. Additionally, code-push seems to break with this 2.x version of ionic-webview. So there may be some decent reasons to stay on 1.2.1. https://github.com/Microsoft/cordova-plugin-code-push/issues/451 – BRass Oct 01 '18 at 14:44
  • Thanks, you saved my day – Chris Oct 30 '18 at 16:10
  • So many "solutions" and this was the final one to work. Thank you! – Low Nov 21 '18 at 09:24
7

When Ionic is used with Capacitor, we can get the correct path of an image or other resource on a native device by:

import { Capacitor } from '@capacitor/core';

Capacitor.convertFileSrc(filePath); 

https://ionicframework.com/docs/core-concepts/webview

Esdras Vitor
  • 161
  • 1
  • 5
2

The only thing that worked for me was convertFileSrc()

let win: any = window; let safeURL = win.Ionic.WebView.convertFileSrc(this.file.dataDirectory+'data/yourFile.png');

Hope this helps

tacticalmovephase
  • 1,119
  • 9
  • 16
1

Try This:

1) https://devdactic.com/ionic-2-images/ In this tutorial, ionic 2 & ionic 3 is the best way to upload and upload images.

2) https://devdactic.com/ionic-4-image-upload-storage/ In this tutorial, ionic 4 is the best way to upload and upload images.

i also use these... and it working fine...

And I have also faced the problem of

not allowed to load local resource

You can see here : @ionic/angular 4.0.0-beta.13 : Not allowed to load local resource : with webview 2.2.3 - Ionic CLI 4.3.1

Ashish Patidar
  • 97
  • 1
  • 13
0

Try this:

const options: CameraOptions = {
    quality: 10
    , destinationType: this.camera.DestinationType.DATA_URL
    , mediaType: this.camera.MediaType.PICTURE
    // Optional , correctOrientation: true
    , sourceType: sourceType == 0 ? this.camera.PictureSourceType.CAMERA : this.camera.PictureSourceType.PHOTOLIBRARY
    // Optional , saveToPhotoAlbum: true
};

this.camera.getPicture(options).then(imageBase64 => {
    let txtForImage = `data:image/jpeg;base64,` + imageBase64;
    this.imageToLoad = txtForImage;
})
.catch(error => {
    alert("Error: " + error);
    console.error(error);
});
Koken
  • 102
  • 6
0

Copy this line into your index.html

<meta http-equiv="Content-Security-Policy" content="default-src *; 
style-src 'self' 'unsafe-inline'; 
script-src 'self' 'unsafe-inline' 'unsafe-eval';
img-src 'self' data: https://s-media-cache-ak0.pinimg.com;
script-src 'self' https://maps.googleapis.com;" />

Then, write this function instead of your one, note that what this script does is returning the photo as base64

getImageFromCamera() {
const options: CameraOptions = {
    quality: 20,
    saveToPhotoAlbum: true,
    destinationType: this.camera.DestinationType.FILE_URI,
    sourceType: this.camera.PictureSourceType.CAMERA,
    encodingType: this.camera.EncodingType.JPEG,
    allowEdit: false
};
this.camera.getPicture(options).then((imageData) => {
    this.imageURI = imageData;
    this.imageName = imageData.substr(imageData.lastIndexOf('/') + 1);
    // Create a folder in memory location
    this.file.checkDir(this.file.externalRootDirectory, 'Demo')
        .then(() => {
            this.fileCreated = true;
        }, (err) => {
            console.log("checkDir: Error");
            this.presentToast("checkDir Failed");
        });
    if (this.fileCreated) {
        this.presentToast("Directory Already exist");
    }
    else {
        this.file.createDir(this.file.externalRootDirectory, "Demo", true)
            .then((res) => {
                this.presentToast("Directory Created");
            }, (err) => {
                console.log("Directory Creation Error:");
            });
    }

    //FILE MOVE CODE
    let tempPath = this.imageURI.substr(0, this.imageURI.lastIndexOf('/') + 1);
    let androidPath = this.file.externalRootDirectory + '/Bexel/';
    this.imageString = androidPath + this.imageName;

    this.file.moveFile(tempPath, this.imageName, androidPath, this.imageName)
        .then((res) => {
            this.presentToast("Image Saved Successfully");
            this.readImage(this.imageString);

        }, (err) => {
            console.log("Image Copy Failed");
            this.presentToast("Image Copy Failed");
        });
    //Complete File Move Code

    this.toDataURL(this.imageURI, function (dataUrl) {
        console.log('RESULT:' + dataUrl);
    });
  }, (err) => {
    console.log(JSON.stringify(err));
    this.presentToast(JSON.stringify(err));
  });
}
presentToast(msg) {
let toast = this.toastCtrl.create({
    message: msg,
    duration: 2000
});
toast.present();
}
toDataURL(url, callback) {
let xhr = new XMLHttpRequest();
xhr.onload = function () {
    let reader = new FileReader();
    reader.onloadend = function () {
        callback(reader.result);
    };
    reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
readImage(filePath) {
let tempPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let imageName = filePath.substr(filePath.lastIndexOf('/') + 1);

this.file.readAsDataURL(tempPath, imageName)
    .then((res) => {
        this.presentToast("Image Get Done");
        this.imageUrl = res;
    }, (err) => {
        this.presentToast("Image Get Error");
    });
}

It sees like it's an issue with content CSP (content security policy), the meta tag should fix this issue, then the code will read the photo as base64, then here you go, in HTML:

<img [src]="imageUrl">

And you can modify the function to remove unnecessary console.log, i was just testing.

Mohamed Wahshey
  • 422
  • 1
  • 6
  • 24
0

All I had to do was use the proper Imagepicker Options, the output type did it:

  const options: ImagePickerOptions = {
    maximumImagesCount: 1,
    outputType: 1,
    quality: 50
  };
Oscar Bout
  • 690
  • 5
  • 19
0
let win: any = window; // hack ionic/angular compilator
var myURL = win.Ionic.WebView.convertFileSrc(myURL);
Jason Aller
  • 3,541
  • 28
  • 38
  • 38