我正在尝试使用文件传输插件文件在Ionic 3中实现下载功能,按照此处的说明https://ionicframework.com/docs/native/file-transfer/。这是代码,
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Platform, AlertController } from 'ionic-angular';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
@IonicPage()
@Component({
selector: 'page-details',
templateUrl: 'details.html',
providers: [FileTransfer, FileTransferObject],
})
export class DetailsPage {
storageDirectory: string = '';
constructor(public navCtrl: NavController, public navParams: NavParams, public platform: Platform, private transfer: FileTransfer, public alertCtrl: AlertController) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad DetailsPage');
}
downloadImage(imageURL) {
this.platform.ready().then(() => {
imageURL = 'https://res.cloudinary.com/beinspired/image/upload/fl_attachment/v1514410469/l98gddyf9uoj7k9bljqi.jpg';
const fileTransfer: FileTransferObject = this.transfer.create();
const imageName = imageURL.split('/').pop();
fileTransfer.download(imageURL, this.storageDirectory + imageName).then((entry) => {
const alertSuccess = this.alertCtrl.create({
title: `Download Succeeded!`,
subTitle: `${imageURL} was successfully downloaded to: ${entry.toURL()}`,
buttons: ['Ok']
});
alertSuccess.present();
}, (error) => {
const alertFailure = this.alertCtrl.create({
title: `Download Failed!`,
subTitle: `${imageURL} was not successfully downloaded. Error code: ${error.code}`,
buttons: ['Ok']
});
alertFailure.present();
});
});
}
}
抛出错误代码1.根据文档,它是FILE_NOT_FOUND_ERR: 1
。但正如您所看到的,指定的URL中存在一个文件。
我尝试使用不同的网址,网址encodeURI()
,但注意到有效。任何有关这方面的帮助都会非常有用,非常感谢。
答案 0 :(得分:2)
对于收到此错误的任何人,我建议在控制台中打印错误并通过chrome调试器查看。在我的情况下,它打印,
{
body: null
code: 1
exception: "/l98gddyf9uoj7k9bljqi.jpg (Read-only file system)"
http_status: 200
source: "https://res.cloudinary.com/beinspired/image/upload/v1514410469/l98gddyf9uoj7k9bljqi.jpg"
target: "l98gddyf9uoj7k9bljqi.jpg"
}
所以,这是因为我错过了初始化storageDirectory
的原因,所以它试图将它存储在只具有只读访问权限的文件系统的根文件夹中。所以,添加后,
this.platform.ready().then(() => {
if(!this.platform.is('cordova')) {
return false;
}
if (this.platform.is('ios')) {
this.storageDirectory = this.file.externalDataDirectory;
}
else if(this.platform.is('android')) {
this.storageDirectory = this.file.externalDataDirectory;
}
else {
return false;
}
});
到构造函数,一切都很好。