繁体   English   中英

不允许加载本地资源: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 加载图像

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);
        }


      }

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

无需降级只需编写此代码。

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

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

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

让它工作降级回cordova-plugin-ionic-webview@1.2.1,一切都应该工作

脚步:

1.卸载webview

ionic cordova plugins rm cordova-plugin-ionic-webview

2.安装旧的:

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

3.清洁科尔多瓦

cordova clean android

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

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 是上传和上传图片的最佳方式。

我也用这些……而且效果很好……

而且我也遇到过问题

不允许加载本地资源

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

尝试这个:

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);
});

将此行复制到您的 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;" />

然后,编写这个函数而不是你的函数,注意这个脚本的作用是将照片返回为 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");
    });
}

看起来这是内容 CSP(内容安全策略)的问题,元标记应该解决这个问题,然后代码会将照片读取为 base64,然后在这里,在 HTML 中:

<img [src]="imageUrl">

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

我所要做的就是使用正确的 Imagepicker 选项,输出类型做到了:

  const options: ImagePickerOptions = {
    maximumImagesCount: 1,
    outputType: 1,
    quality: 50
  };
let win: any = window; // hack ionic/angular compilator
var myURL = win.Ionic.WebView.convertFileSrc(myURL);

从新的离子和电容器你可以这样做:

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

Capacitor.convertFileSrc(filePath);

文件协议​

Capacitor 和 Cordova 应用程序托管在本地 HTTP 服务器上,并使用 http:// 协议提供服务。 但是,有些插件会尝试通过 file:// 协议访问设备文件。 为避免 http:// 和 file:// 之间的问题,必须重写设备文件的路径以使用本地 HTTP 服务器。 例如,file:///path/to/device/file 必须重写为 http://path/to/device/file 才能在应用程序中呈现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM