Не разрешается загружать локальный ресурс: ionic 3 android - PullRequest
0 голосов
/ 28 августа 2018

Я использую apk для сборки andon 3 android и пытаюсь загрузить изображение из файла: ///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

Ответы [ 6 ]

0 голосов
/ 03 июля 2019

Все, что мне нужно было сделать, это использовать правильные параметры Imagepicker, тип вывода сделал это:

  const options: ImagePickerOptions = {
    maximumImagesCount: 1,
    outputType: 1,
    quality: 50
  };
0 голосов
/ 01 мая 2019

Нет необходимости понижать версию, просто напишите этот код.

private win: any = window;
    this.win.Ionic.WebView.convertFileSrc(path);
0 голосов
/ 22 ноября 2018

Попробуйте:

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: запрещено загружать локальный ресурс: с веб-обзором 2.2.3 - Ionic CLI 4.3.1

0 голосов
/ 02 октября 2018

Скопируйте эту строку в ваш 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, я только что тестировал.

0 голосов
/ 01 октября 2018

У меня были те же проблемы, и оказалось, что Новый плагин ionic webview является причиной проблемы.

Новый плагин: cordova-plugin-ionic-webview @ 2.x кажется нестабильным ...

чтобы все заработало, вернитесь обратно к cordova-plugin-ionic-webview@1.2.1 и все должно работать

Шаги:

1. удалить веб-просмотр

ionic cordova plugins rm cordova-plugin-ionic-webview

2. установить старую:

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

3. чистая кордова

cordova clean android
0 голосов
/ 26 сентября 2018

Попробуйте это:

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