关于文件:不允许加载本地资源:ionic 3 android

Not allowed to load local resource: ionic 3 android

我正在使用ionic 3 android build apk并尝试从file:///storage/emulated/0/data/io.ionic.vdeovalet/cache/image.jpeg加载图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    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);
        }


      }

错误:不允许加载本地资源
android 6.0.1


No Need To Downgrade just write this code.

1
2
private win: any = window;
    this.win.Ionic.WebView.convertFileSrc(path);


我有同样的问题,事实证明
新的ionic webview插件是问题的原因。

新的插件:cordova-plugin-ionic-webview @ 2.x似乎不稳定...

为了使其工作降级到[email protected],所有都应该工作

脚步:

1.卸载webview

1
ionic cordova plugins rm cordova-plugin-ionic-webview

2.安装旧的:

1
ionic cordova plugins add [email protected]

3.清洁科尔多瓦

1
cordova clean android


当Ionic与Capacitor一起使用时,我们可以通过以下方式获取本机设备上图像或其他资源的正确路径:

1
2
3
import { Capacitor } from '@capacitor/core';

Capacitor.convertFileSrc(filePath);

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


唯一对我有用的是convertFileSrc()

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

希望这可以帮助


尝试这个:

1)https://devdactic.com/ionic-2-images/
在本教程中,ionic 2和ionic 3是上载和上载图像的最佳方法。

2)https://devdactic.com/ionic-4-image-upload-storage/在本教程中,ionic 4是上载和上载图像的最佳方法。

我也使用这些...并且工作正常...

而且我还面临着

not allowed to load local resource

您可以在这里看到:
@ ionic / angular 4.0.0-beta.13:不允许加载本地资源:使用Webview 2.2.3-Ionic CLI 4.3.1


1
2
let win: any = window; // hack ionic/angular compilator
var myURL = win.Ionic.WebView.convertFileSrc(myURL);

我所要做的就是使用适当的Imagepicker选项,输出类型可以做到这一点:

1
2
3
4
5
  const options: ImagePickerOptions = {
    maximumImagesCount: 1,
    outputType: 1,
    quality: 50
  };

将此行复制到您的index.html中

1
2
3
4
5
<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;" />

然后,编写此函数而不是您的函数,请注意,此脚本执行的操作是将照片返回为base64

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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");
    });
}

看起来好像是内容CSP(内容安全策略)存在问题,meta标签应该可以解决此问题,然后代码会将照片读取为base64,然后使用HTML编写:

1
<img [src]="imageUrl">

您可以修改该功能以删除不必要的console.log,而我只是在测试。


尝试这个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
});