C# 从WebAPI核心下载文件-Angular 7

C# 从WebAPI核心下载文件-Angular 7,c#,asp.net-web-api,asp.net-core,asp.net-core-webapi,angular7,C#,Asp.net Web Api,Asp.net Core,Asp.net Core Webapi,Angular7,我试图从服务器下载一个文件,但该文件没有显示其原始内容,而是显示[object] WEB API核心 [Authorize(AuthenticationSchemes = "Bearer")] [HttpGet] public HttpResponseMessage DownloadContractFile(string fileName) { string contentRootPath = _hostingEnvironment.ContentRootPath; var fo

我试图从服务器下载一个文件,但该文件没有显示其原始内容,而是显示[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;
    }
}
角度代码:服务方法

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

  }
Component.html

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

收到的答复

收到的文件内容


这是我在项目中下载文件时使用的代码

控制器代码:

    [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();
        }
    }

如果仔细查看,可能会发现该方法受到保护:
[Authorize(AuthenticationSchemes=“Bearer”)]
。如何使用授权传输标题?
    [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");