下载离子文件会出现类似错误代码1的错误

时间:2018-12-16 14:48:13

标签: cordova ionic-framework ionic3 file-transfer

我在离子项目中使用ionic-file-trasnfer,与以下文档使用相同的内容:-

download() {
  const url = 'http://www.example.com/file.pdf';
  fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
    console.log('download complete: ' + entry.toURL());
  }, (error) => {
    // handle error
  });
}

但是,我得到了错误代码1。它出现在错误回调函数中,而不是成功回调中

2 个答案:

答案 0 :(得分:1)

您必须在此函数中创建新的文件传输对象。请找到以下代码

import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';

constructor(private transfer: FileTransfer, private file: File, private fileOpener: FileOpener) { }

...
download() {

 const url = 'http://www.example.com/file.pdf';
 const fileTransfer: FileTransferObject = this.transfer.create();
  fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
    console.log('download complete: ' + entry.toURL());
     this.fileOpener.open(entry.toURL(), 'application/pdf')
  .then(() => console.log('File is opened'))
  .catch(e => console.log('Error opening file', e));
  }, (error) => {
    // handle error
  });

要打开文件,您必须添加fileOpener插件(https://ionicframework.com/docs/native/file-opener/),我刚刚更新了代码,请对其进行检查。

希望这对您有帮助!

答案 1 :(得分:0)

import { DocumentViewer} from '@ionic-native/document-viewer';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import {File} from '@ionic-native/file';
import {Toast} from '@ionic-native/toast';

constructor(private document:DocumentViewer, private file: File, private transfer: FileTransfer, private toast: Toast){}

.....

public download() {
        let path = null;
            if(this.platform.is('ios')){
                path = this.file.documentsDirectory;
            }else if(this.platform.is('android')){
                path = this.file.dataDirectory;
            }
            const fileTransfer: FileTransferObject = this.transfer.create();
            fileTransfer.download('http://www.example.com/file.pdf',path + 'file.pdf').then((entry)=>{
                let url = entry.toURL();
                this.toast.show('Download Complted', '5000','center').subscribe(
                    toast=>{
                        console.log(toast);
                    }
                );
                this.document.viewDocument(url, 'application/pdf', {});
            });
        }

我对您的代码进行了一些编辑,您可以看一下此代码。希望对您有帮助。