从 Web API 核心下载文件 - Angular 7

Posted

技术标签:

【中文标题】从 Web API 核心下载文件 - Angular 7【英文标题】:Download file from Web API Core - Angular 7 【发布时间】:2019-08-03 16:12:31 【问题描述】:

我正在尝试从服务器下载文件,但该文件未显示其原始内容,而是显示 [object Object]。

WEB API 核心

[Authorize(AuthenticationSchemes = "Bearer")]
[HttpGet]
public HttpResponseMessage DownloadContractFile(string fileName)

    string contentRootPath = _hostingEnvironment.ContentRootPath;
    var folderName = Path.Combine(contentRootPath, FileHandler.ContractFilePath, Convert.ToInt32(User.Identity.Name).ToString());

    var path = Path.Combine(folderName, fileName);

    var memory = new MemoryStream();

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    using (var stream = new FileStream(path, FileMode.Open))
    
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(path);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue(FileHandler.GetContentType(path)); // Text file
        result.Content.Headers.ContentLength = stream.Length;

        return result;
    

Angular 代码:服务方法

  downloadContractFile(fileName: string) 

    const obj: any =  fileName: fileName ;

    const httpParams: HttpParamsOptions =  fromObject: obj  as HttpParamsOptions;

    const httpOptions = 
      params: new HttpParams(httpParams),
      headers: new HttpHeaders(
        'Content-Type': 'application/octet-stream',
        'Authorization': 'Bearer ' + this.jwt.getToken
      )
    ;   


    return this.http.get<Array<any>>(`$this.settings.getApiSettings('uri')/api/contract/DownloadContractFile`, httpOptions).map( /// <<<=== use `map` here
      (response) => 

        if (response["status"] == 401) 
          this.jwt.redirectToLogin();
        
        else if (response["status"] < 200 || response["status"] >= 300) 
          throw new Error('This request has failed ' + response["status"]);
        
        let data = response;
        return data;
      
    );

  

组件.ts

  downloadFile(fileName) 

    this.js.checkTokenValid().subscribe(res => 

      if (res == null)
        this.js.redirectToLogin();
      else 

        this.conc.downloadContractFile(fileName).subscribe(respData => 

          console.log(respData);

          this.type = respData.content["headers"][1]["value"][0];

          this.downFile(respData.content, this.type, fileName);

        , error => 

        );

      
    );

  

  downFile(data: any, type: string, fileName: string) 

    var blob = new Blob([data],  type: type );
    var url = window.URL.createObjectURL(blob);

    saveAs(blob, fileName);

    //var fileURL = URL.createObjectURL(res);
    //window.open(fileURL); // if you want to open it in new tab

  

组件.html

<a href="javascript:void(0)" (click)="downloadFile(item.fileName);">download file</a>

收到回复

收到的文件内容

【问题讨论】:

Return file in ASP.Net Core Web API的可能重复 【参考方案1】:

这是我在项目中用来下载文件的代码。

控制器代码:

    [HttpGet("DownloadFile")]
    public async Task<IActionResult> DownloadFile(string fileName = "")
    
        var response = await DownloadFileFromDatabase(fileName);
        if (response.IsSuccessStatusCode)
        
            System.Net.Http.HttpContent content = response.Content;
            var contentStream = await content.ReadAsStreamAsync();
            var audioArray = ReadFully(contentStream);
            return Ok(new  response = audioArray, contentType = "audio/wav", fileName );
        
        else
        
            throw new FileNotFoundException();
        
    

客户端代码:

  HandleBase64  (data , contentType,fileName ) 
    let byteCharacters = atob(data);    
    let byteNumbers = new Array(byteCharacters.length);    
    for (var i = 0; i < byteCharacters.length; i++) 
        byteNumbers[i] = byteCharacters.charCodeAt(i);

    let byteArray = new Uint8Array(byteNumbers);    
    let blob = new Blob([byteArray], type: contentType);
    if(contentType === "audio/wav")
        var blobURL=URL.createObjectURL(blob);
        window.open(blobURL);       
    
    else
        var blobURL = window.URL.createObjectURL(blob);
        var anchor = document.createElement("a");
        anchor.download = fileName;
        anchor.href = blobURL;
        anchor.click();
    

您也可以在控制器端使用文件流简单地返回文件。这将自动下载不需要在客户端处理的文件

    return File(stream, "application/octet-stream"); 

【讨论】:

如果你仔细观察会发现该方法是受保护的:[Authorize(AuthenticationSchemes = "Bearer")]。如何通过授权传输标头?

以上是关于从 Web API 核心下载文件 - Angular 7的主要内容,如果未能解决你的问题,请参考以下文章

从 Angular js 中的 web api 下载 csv 文件

使用 closedxml 从 web api 下载 excel 文件

如何使用 jQuery Ajax 调用从 ASP.NET Web Api 下载 CSV 文件

在 ASP.NET MVC 5 控制器中使用 POST 从 dotnet Core Web API 下载文件

如何从 ASP.NET 核心 mvc 向 asp.net 核心中的 Web API 发出 PUT 请求?

如何在asp.net核心中从客户端调用web api方法?