Angular保存下载文件

时间:2018-09-20 19:46:56

标签: php angular download

我正在编写一个带有角度前端和php后端的web应用,现在它正面临着挑战,当尝试下载文件时,它是通过以下脚本完全加载的。

Angular 服务:

downloadFile(f:string){    
    this.http.post('/api/download.php', JSON.stringify({"file": f}), {responseType:'arraybuffer'})
    .subscribe(response => {
        console.log(response);
    });
}

二手进口:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

PHP 文件如下所示(工作正常):

  include "config/var.inc.php";
  $dir = "../" . DATA_FOLDER . "/";
  $data = json_decode(file_get_contents("php://input"));
  $file = $dir . $data->file;

  if(file_exists($file)){
    header('Content-Description: download audio');
    header('Content-Type: audio/mpeg');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
  }

console.log显示文件已完全加载(23300766字节) enter image description here

如何将其作为下载文件交付给用户?

1 个答案:

答案 0 :(得分:0)

您可以使用文件保存器https://www.npmjs.com/package/file-saver

这是我的代码:

import * as FileSaver from 'file-saver';

downloadTemplate(filePath: string) { // Example: filePath = '/file-path/download.docx'
    this.http.post(`http://endpoint/download`, filePath, { observe: 'response', responseType: 'blob' })
        .subscribe((response) => {
            this.saveFile(response);
        });
}

private saveFile(response) {
    const fileName = this.getFileNameFromHttpResponse(response);
    FileSaver.saveAs(response.body, fileName);
}

private getFileNameFromHttpResponse(httpResponse) {
    const contentDispositionHeader = httpResponse.headers.get('Content-Disposition');
    const result = contentDispositionHeader.split(';')[1].trim().split('=')[1];
    return result.replace(/"/g, '');
}

注意:如果要从响应中获取文件名,则需要添加此文件(“ Access-Control-Expose-Headers 内容-处置”)到服务器的响应标头。