typescript - 如何在不使用 FileTransfer 的情况下从 Ionic 5 中的 url 下载文件
问题描述
我目前正在开发 Ionic 应用程序并停留在文件下载部分。我看到很多帖子都表示FileTransfer
现在不推荐使用 Cordova 库以支持 XHR 请求。
尽管我看到很多帖子说该库已被弃用,但我找不到任何示例代码(用于从 URL 下载文件)。
谁能建议我在不使用FileTransfer
插件的情况下从 url 下载文件的好方法?
解决方案
从另一台服务器下载文件可能会导致恼人的CORS错误,这主要是我们无法控制的。最安全的方法是绕过 Webview 并本地下载文件。你可以使用Native HTTP插件
在 Ionic 4 或更高版本中使用将如下所示:
import { Component } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';
import { File } from '@ionic-native/file/ngx';
@Component({
selector: 'app-home',
templateUrl: './you-file.html',
styleUrls: ['./your-file.scss'],
})
export class HomePage {
constructor(private nativeHTTP: HTTP, private file: File) {}
private downloadFileAndStore() {
//
const filePath = this.file.dataDirectory + fileName;
// for iOS use this.file.documentsDirectory
this.nativeHTTP.downloadFile('your-url', {}, {}, filePath).then(response => {
// prints 200
console.log('success block...', response);
}).catch(err => {
// prints 403
console.log('error block ... ', err.status);
// prints Permission denied
console.log('error block ... ', err.error);
})
}
}
}
推荐阅读
- java - 如何在 MongoDB 中的多个表之间指定 @CollectionTable 关系?
- docker - 尝试恢复结构网络时出现权限被拒绝错误
- angular - 当我单击 Angular 中的按钮时,如何输入我在输入字段中写的内容?
- android - 在输入密码之前通知用户要求的最佳方法是什么?
- powershell - 使用 powershell Get-Content 从文本文件中读取日期和时间
- sql-server - 如何限制用户从客户端本地计算机访问 SQL Server 数据库?
- plot - 如何在散景中设置轴标签和轴之间的距离?
- linux - 将所有 .tar 和 .tar.bz2 文件系统从所有子目录复制到另一个目录
- graph - 如何更改 Janusgraph 客户端读取一致性?
- sql - 创建函数“COPY EMPLOYEES_WITH_REC”,使用记录类型将数据从 EMPLOYEES 表复制到 JRF _EMPLOYEES 表