Плагин файлов Ionic V4 (бета-версия 11), похоже, плохо работает с V4 - PullRequest
0 голосов
/ 01 октября 2018

Я пытаюсь загрузить изображение из Интернета на мобильный телефон через ionic V4, а затем показать, что загруженное изображение напрямую из родной файловой системы с помощью плагина File для тега.

К сожалению, я не могу заставить его работать в V4 ... но он работает в V3.Я думаю, что может быть проблема с тем, как V4 интерпретирует путь, чтобы связать его с атрибутом src (?)

Я написал программу для его проверки.

TSfile:

import { Component, OnInit } from '@angular/core';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { File } from '@ionic-native/file/ngx'

@Component({
  selector: 'app-scratch2',
  templateUrl: './scratch2.page.html',
  styleUrls: ['./scratch2.page.scss'],
})
export class Scratch2Page implements OnInit {
  private address: string = null;
  private path: string = null;
  private fileNumber = 1;
  private latest = null;
  private toggle = false;

  constructor(
    private fileX: FileTransfer,
    private file: File
  ) { 
    this.path = this.file.dataDirectory + "files/";
  }

  ngOnInit() {
    let filename = this.nameFile()
    this.latest = this.nameFix(filename)
    console.log("1the filename that is returned is ********** ", filename)
  }

  nameFile(){
    let filename = this.path + "file" + this.fileNumber
    return filename
  }

  nameFix(filename){
    return filename.replace(/file:\/\//g, "")
  }

  downloadFile() {
    let filename = this.nameFile();
    console.log("2the filename that is returned is ********** ", filename)
    console.log("Entered download File with url: ", this.address)
    let url = this.address
    const fileTransfer: FileTransferObject = this.fileX.create();
    fileTransfer.download(url, filename).then((entry) => {
        console.log('fileTransfer.download data ** ** ** **:' + JSON.stringify(entry));
        this.fileNumber += 1;
        this.latest = this.nameFix(filename)
    }, (err) => {
      // handle error
      console.log("downloadfile() error: " + JSON.stringify(err));
    });
  }

  toggleToggle(){
    this.toggle = !this.toggle;

  }

}

А вот HTML-файл:

    <ion-header>
  <ion-toolbar>
      <ion-buttons slot="start">
          <ion-back-button defaultHref="/"></ion-back-button>
        </ion-buttons>
    <ion-title>scratch2</ion-title>
  </ion-toolbar>
  <ion-toolbar>{{latest}} {{toggle}}</ion-toolbar>
</ion-header>

<ion-content padding>
    <ion-item>
        <ion-label>Address</ion-label>
        <ion-input placeholder="Enter address" [(ngModel)]="address"></ion-input>
      </ion-item>
      <ion-button (click)="downloadFile()"> Download from address</ion-button>
      <ion-button (click)="toggleToggle()">Toggle</ion-button>

    <img *ngIf="toggle" [src]="latest"/>
</ion-content>

Любая помощь будет признательна

1 Ответ

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

Отвечая на мой собственный вопрос здесь ... вот что я нашел.

Структура файла изменилась, и к самим файлам можно получить доступ через веб-сервер, а не напрямую.Об этом говорится по этой ссылке: https://ionicframework.com/docs/wkwebview/

Что сводится к следующему: Когда вы хотите загрузить файл на телефон, вы делаете это с помощью этих двух путей, один для загрузки файла,и другой для отображения загруженного файла:

this.downloadPath = this.file.dataDirectory + "filename.jpg"
this.showFilePath = normalizeURL(this.file.dataDirectory + "filename.jpg")

, где normalizeURL импортируется с: import {normalizeURL} из «ionic-angular»;

Итак, я переписал приведенный выше код, чтобы посмотретькак это:

ФАЙЛ ТС

import { Component, OnInit } from '@angular/core';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { File } from '@ionic-native/file/ngx'
import { normalizeURL } from "ionic-angular";

@Component({
  selector: 'app-scratch2',
  templateUrl: './scratch2.page.html',
  styleUrls: ['./scratch2.page.scss'],
})
export class Scratch2Page implements OnInit {
  private address: string = null;
  private path: string = null;
  private toggle = false;
  private showPath = null;
  private downloadPath = null

  constructor(
    private fileX: FileTransfer,
    private file: File
  ) {
    this.path = this.file.dataDirectory + "files/";
    this.downloadPath = this.path + "beer.jpg"
    this.showPath = normalizeURL(this.path + "beer.jpg")
  }
  ngOnInit() {
  }

  downloadFile() {
    console.log("Entered download File with url: ", this.address)
    let url = this.address
    const fileTransfer: FileTransferObject = this.fileX.create();
    fileTransfer.download(url, this.downloadPath).then((entry) => {
      console.log('fileTransfer.download data ** ** ** **:' + JSON.stringify(entry));
    }, (err) => {
      console.log("downloadfile() error: " + JSON.stringify(err));
    });
  }

  toggleToggle() {
    this.toggle = !this.toggle;
  }
}

ФАЙЛ HTML

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button defaultHref="/"></ion-back-button>
    </ion-buttons>
    <ion-title>scratch2</ion-title>
  </ion-toolbar>
  <ion-toolbar>toggle:{{toggle}} <br><br> download path:<br>{{downloadPath}} <br><br> Show path:<br>{{showPath}}</ion-toolbar>
</ion-header>
<ion-content padding>
  <ion-item>
    <ion-label>http address of jpg:</ion-label>
    <ion-input placeholder="Enter address" [(ngModel)]="address"></ion-input>
  </ion-item>
  <ion-button (click)="downloadFile()"> download jpg</ion-button>
  <ion-button (click)="toggleToggle()">Toggle</ion-button>
  <img *ngIf="toggle" src="{{showPath}}" />
</ion-content>

На симуляторе iPhone путь загрузки начинается так:

file:///Users/myUserName/Library/etc etc etc

и путь к отображаемому файлу начинается следующим образом:

http://localhost:8080/_file_/Users/myUserName/Library/etc etc etc
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...