用angular js

时间:2018-12-20 04:32:22

标签: android angularjs cordova hybrid-mobile-app

在Angularjs移动应用程序(平台Cordova)中,如何在从服务器提供URL的同时在移动设备中下载文件。该文件可以是pdf,图像等类型。

1 个答案:

答案 0 :(得分:0)

您必须执行以下操作:

这是Angular JS部分:

import { Http, ResponseContentType } from '@angular/http';
...

constructor(
  private http: Http,
) { }

downloadFile() {
  return this.http
    .get('http://www.africau.edu/images/default', {
      responseType: ResponseContentType.Blob,
      search: // query string if have
    })
    .map(res => {
      return {
        filename: 'sample.pdf',
        data: res.blob()
      };
    })
    .subscribe(res => {
        console.log('start download:',res);
        var url = window.URL.createObjectURL(res.data);
        var a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display: none');
        a.href = url;
        a.download = res.filename;
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove(); // remove the element
      }, error => {
        console.log('download error:', JSON.stringify(error));
      }, () => {
        console.log('Completed file download.')
      });
}

这是HTML部分:

<button class="btn btn-primary" (click)="downloadFile()"><i class="fa fa-file-pdf-o"></i> Download</button>