簡體   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