【问题标题】:File download in angular jsAngular js中的文件下载
【发布时间】:2019-05-20 14:33:57
【问题描述】:

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

【问题讨论】:

标签: android angularjs cordova hybrid-mobile-app


【解决方案1】:

你必须这样做:

这是 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    相关资源
    最近更新 更多