我需要从服务器下载文件。我以前使用过Ionic的FileTransfer插件,并且运行良好。我还可以获得尺寸的下载进度。
this.fileTransfer.download(url, savePath, false, options).then((entry) => {
console.log("download completed => "+ entry)
}, (error) => {
console.log("File download error => "+JSON.stringify(error))
});
但是我需要捕获我无法使用的ResponseHeader。此外,现在不建议使用此FileTranser。
所以我转到了本地Http(@ionic-native/http
)。使用downloadFile
功能,我可以下载文件,但无法获取响应头以及下载进度。
import { HTTP } from '@ionic-native/http';
在下载功能中,
this.nHttp.downloadFile(url, {}, "", savePath)
.then(x => {
console.log("download completed => "+ x)
}
}, (error) => {
console.log("File download error => + JSON.stringify(error))
});
然后我尝试通过Angular http使用HttpEvents。此方法具有获取Response标头的事件,但tt导致CORS问题。不知道为什么会导致CORS问题,因为其他两种方法都可以下载文件。
const req = new HttpRequest('GET', Url, {
reportProgress: true,
observe: 'events',
headers: new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Access-Control-Allow-Headers', 'Content-Length')
.set('Access-Control-Expose-Headers', 'Content-Length')
//responseType: "blob"//blob type pls
});
//all possible events
this.http.request(req).subscribe((event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Sent:
console.log('Request sent!');
break;
case HttpEventType.ResponseHeader:
console.log('Response header received!');
break;
case HttpEventType.DownloadProgress:
//i use a gloal progress variable to save progress in percent
//this.progress = Math.trunc(event.loaded / event.total * 100);
//Math.trunc(event.loaded / event.total * 100);
break;
case HttpEventType.Response:
//do whatever you have to do with the file using event.body
console.log(' Done!', event.body);
//i'm gonna write the file in my case
this.file.writeFile(aPath, aName, event.body, {replace: true}).then( (file) =>{
function onFileImageSuccess(){
//in case of file success
console.log("file download success");
}
function onFileImageError(error) {
//in case of Filesaver fail
console.log("File download failed "+error);
}
}).catch(
(err) => {
//in case of file.writefile fail
console.log("File download Error "+err);
});
}
});
我还使用了有角度的Http Get来下载angular-request-file中给出的文件。它不会以成功(承诺)或错误/ catch块结束。
return this.http.get(attachmentName, {responseType: 'text'})
.pipe(
tap( // Log the result or error
data => {
console.log("File downloaded ~~~~ "+data);
},
error => {
console.log("Error in download ~~~~~ "+error);
}
)
).catch((err: any, caught: Observable<any>):ObservableInput<{}> => {
return Observable.throw(err.statusText);
})
我要寻找的问题的答案是,如何使用Response标头下载文件以及下载进度。谢谢。