首页 > 解决方案 > 使用 asp.net core 2.1 在 angular 8 中下载文件总是会给出损坏的文件

问题描述

我在我的项目中使用asp.net core 2.1,客户端使用angular 8,但无法为downolad文件制作功能,下载时只能下载.txt文件,无法下载.pdf,.excell,image等。下面是我的代码。

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;
    }
}   

标签: c#angular8asp.net-core-2.1

解决方案


一旦我在调用中指定类型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);
}

推荐阅读