使用 asp.net 核心 2.1 下载 angular 8 中的文件总是给出损坏的文件

downolading a file in angular 8 using asp.net core 2.1 always give corrupted file

我在我的项目中使用 asp.net core 2.1,客户端使用 angular 8 但无法为下载文件创建功能,下载时只能下载 .txt 文件而无法下载.pdf,.excell,image etc.Below 是我的代码。

downloadFiles(filename: any) {   
    return this.http.get(this.myAppUrl + 'api/Download/' + filename)
    .catch(this.errorHandler)
}

//after getting response data from server and passing to the method makeDownloadFiles only 
//downloded corrupted file.

makeDownloadFiles(data: any) {
    debugger;
    const blob = new Blob([data]); 
    const url = window.URL.createObjectURL(blob);
    window.open(url);
}

//and server code is 

[HttpGet]
[Route("api/Download/{filename}")]
public FileResult Download(string filename){
    try {
        string extension = filename.Substring(filename.IndexOf('.') + 1);
        string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/files", filename);
        byte[] fileBytes = System.IO.File.ReadAllBytes(path);
        string fileName = filename;
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
    } catch (Exception ex){
        return null;
    }
}   

一旦我在对 get 的调用和对 new Blob 的调用中指定了类型,您的代码就可以正常工作:

downloadFiles(filename: any) {   
    return this.http.get(this.myAppUrl + 'api/Download/' + filename, { responseType: 'blob'})
    .catch(this.errorHandler)
}

makeDownloadFiles(data: any) {
    debugger;
    const blob = new Blob([<any>data], {type: 'application/octet-stream'}); 
    const url = window.URL.createObjectURL(blob);
    window.open(url);
}

试试这个。您不需要调用 api/download 文件的 api。只需获取 FileUrl 并调用以下方法。

 downloadFile(fileNameUrl: any) {

        var filename: string[] = fileNameUrl.split('\');
        this.getImage(fileNameUrl).subscribe((data: Blob) => {
            debugger;
            let item = filename[filename.length - 1];

            let checkFileType = item.split('.').pop();
            var fileType: any;
            if (checkFileType == "txt") {
                fileType = "text/plain";
            }
            if (checkFileType == "pdf") {
                fileType = "application/pdf";
            }
            if (checkFileType == "doc") {
                fileType = "application/vnd.ms-word";
            }
            if (checkFileType == "docx") {
                fileType = "application/vnd.ms-word";
            }
            if (checkFileType == "xls") {
                fileType = "application/vnd.ms-excel";
            }
            if (checkFileType == "xlsx") {
                fileType = "application/vnd.ms-excel";
            }
            if (checkFileType == "png") {
                fileType = "image/png";
            }
            if (checkFileType == "jpg") {
                fileType = "image/jpeg";
            }
            if (checkFileType == "jpeg") {
                fileType = "image/jpeg";
            }
            if (checkFileType == "gif") {
                fileType = "image/gif";
            }
            if (checkFileType == "csv") {
                fileType = "text/csv";
            }
            if (checkFileType == "amr") {
                fileType = "AMR-WB";
            }
            var blob = new Blob([data], { type: fileType })
            const blob1: Blob = data;
            const fileName1: string = item;
            const objectUrl: string = URL.createObjectURL(blob);
            const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;

            a.href = objectUrl;
            a.download = fileName1;
            document.body.appendChild(a);
            a.click();

            document.body.removeChild(a);
            URL.revokeObjectURL(objectUrl);
        })
        }

  getImage(imageUrl: string): Observable<Blob> {
    return this._http.get(imageUrl, { responseType: 'blob' });
  }