Конфликт при использовании версии cordova-plugin-ionic-webview? - PullRequest
3 голосов
/ 23 апреля 2019

Я работаю над приложением ionic3.Мне нужно взять изображение от пользователя с помощью камеры или галереи, сначала сохранить его в локальном каталоге, а затем загрузить изображение на сервер.Я использовал следующий пошаговый учебник: https://devdactic.com/ionic-2-images/ Загрузка фотографии работает как чудо, но при сохранении изображения в локальном каталоге и сохранении пути в локальном хранилище после извлечения из хранилища отображается следующая ошибка: enter image description here.
Поскольку очевидно, что он жалуется на Не разрешено загружать локальный ресурс .Затем я начал поиск решения в Google и обнаружил это решение в StackOverflow и это в GitHub.Как они оба предположили, проблема в cordova-plugin-ionic-webview , поэтому мне нужно понизить версию.Когда я попробовал их решение, загрузка и показ изображения пользователю работают отлично, однако это создает проблему в других частях приложения, которые загружают данные из ресурса независимо от того, что;изображения, шрифты.Показывает следующую ошибку enter image description here. Далее Я нашел решение этой проблемы в GitHub здесь , так как это было предложено и принято большинством пользователей, нам нужно использовать последнюю версию **cordova-plugin-ionic-webview **, что, конечно, вызвало бы у меня первую проблему.Я собираюсь загрузить здесь и эти коды.

getImage() {
    this.presentActionSheet();
  } //end getImage
  public uploadImage() {
    console.log('Uploading the image');
    console.log(this.lastImageL);
    var targetPath = this.pathForImage(this.lastImage);

    console.log(targetPath);

    var url = "https://dev.raihan.pomdev.net/wp-json/raihan/v1/profilePhoto";


    var filename = this.lastImage;
    console.log(' targetPath  :   ', targetPath);
    console.log('File Name : ', filename)
    console.log(url, " IS the URL");
    var options = {
      fileKey: "image",
      fileName: filename,
      chunkedMode: false,
      mimeType: "multipart/form-data",
      params: {
        'image': filename,
        'user_id': 79
      }
    };

    const fileTransfer: TransferObject = this.transfer.create();

    this.loading = this.loadingCtrl.create({
      content: 'منتظر باشید',
    });
    this.loading.present();

    // Use the FileTransfer to upload the image
    fileTransfer.upload(targetPath, url, options).then(data => {
      this.loading.dismissAll()

      this.presentToast(' . عکس شما موفقانه ذخیره شد');

      this.storage.set("Profile_Photo", targetPath).then((data) => {
        console.log('response of uploading the image ', data);
        console.log('Target Path ', targetPath);
        console.log('In set storage ', targetPath);
        $("#Photo").attr("src", targetPath);
        $("#Photo2").attr("src", targetPath);
        console.log('myphoto ', targetPath);
      });
    }, err => {
      this.loading.dismissAll()
      this.presentToast('مشکلی در قسمت ذخیره کردن عکس شما وجود دارد  ' + err);
      console.log('error sending the image');
      console.log(err);
    });
  }
  public takePicture(sourceType) {

    var options = {
      quality: 100,
      sourceType: sourceType,
      saveToPhotoAlbum: false,
      correctOrientation: true
    };

    // Get the data of an image
    this.camera.getPicture(options).then((imagePath) => {

      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());
          });
      } 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.');
    });
  }
  ionViewDidLoad() {
    console.log('ionViewDidLoad CaptureImagePage');
  }
  private createFileName() {
    var d = new Date(),
      n = d.getTime(),
      newFileName = n + ".jpg";
    return newFileName;
  }

  // Copy the image to a local folder
  private copyFileToLocalDir(namePath, currentName, newFileName) {
    this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
      this.lastImage = newFileName;
      this.uploadImage();
    }, error => {
      this.presentToast('Error while storing file. ' + error);
    });
  }

  private presentToast(text) {
    let toast = this.toastCtrl.create({
      message: text,
      duration: 5000,
      position: 'center'
    });
    toast.present();
  }

  // Always get the accurate path to your apps folder
  public pathForImage(img) {
    if (img === null) {
      return '';
    } else {
      return cordova.file.dataDirectory + img;
    }
  }
  public presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
      title: 'Select Image Source',
      buttons: [
        {
          text: 'Load from Library',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
          }
        },
        {
          text: 'Use Camera',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.CAMERA);
          }
        },
        {
          text: 'Cancel',
          role: 'cancel'
        }
      ]
    });
    actionSheet.present();
  }

`Теперь я не понимаю, какую версию ** cordova-plugin-ionic-webview ** мне следует использовать?Кто-нибудь может мне помочь?

Примечание: Спасибо за ваше терпение, чтобы прочитать все вопросы.

1 Ответ

1 голос
/ 23 апреля 2019

Я бы попытался использовать последнюю версию WebView, если это возможно, а затем использовать метод window.Ionic.WebView.convertFileSrc() на пути file:///, прежде чем поместить его на страницу для отображения.Эти советы можно увидеть здесь:

Приложения Cordova и Capacitor размещаются на локальном HTTP-сервере и обслуживаются через http: // протокол.Однако некоторые плагины пытаются получить доступ к файлам устройства через протокол file: //.Чтобы избежать трудностей между http: // и file: //, пути к файлам устройства должны быть переписаны для использования локального HTTP-сервера.Например, файл: /// путь / к / устройству / файлу должен быть переписан как http://://path/to/device/file перед его отображением в приложении.

Для приложений Cordova плагин Ionic Web View предоставляет служебную функцию для преобразованияURI файла: window.Ionic.WebView.convertFileSrc ().Существует также соответствующий плагин Ionic Native: @ ionic-native / ionic-webview.

Вот пример метода, который я использую, который отлично работает в веб-просмотре 4.x:

  getNormalizedUrl(path: string): SafeResourceUrl {
      let newPath = this.domSanitizer.bypassSecurityTrustUrl(
          window.Ionic.WebView.convertFileSrc(path));
      return newPath;
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...