下载文件时浏览器不显示进度条

Ant*_*lia 5 c# asp.net file asp.net-web-api angular

我有一个带有 ASP.NET Web API 的 Angular 应用程序。

我想下载存储在我的服务器上的文件。目前,这是我的代码:

[HttpGet]
[Route("downloadFile")]
[JwtAuthentication] //Only a connected user can download the file
public async Task<HttpResponseMessage> DownloadFile(string path)
{
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var fileStream = File.OpenRead(path);
    result.Content = new StreamContent(fileStream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentLength = fileStream.Length;
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = fileStream.Name,
        Size = fileStream.Length
    };
    return result;
}
Run Code Online (Sandbox Code Playgroud)

在我的角度代码中:

// file-navigation.service.ts
downloadFile(file: FileElement) {
    const data = { path: this.formatPath(true) + file.name };
    return this.http.get(this.apiUrl + '/downloadFile', { params: data, responseType: 'blob' });
}

// file-navigation.component.ts
this.fileNavigationService.downloadFile(element).subscribe(result => {
    this.generateDownload(element, result, false);
});

generateDownload(element: FileElement, blob: Blob, isArchive: boolean) {
    const fileName = element != null ? element.name : 'Archive';
    if (navigator.appVersion.toString().indexOf('.NET') > 0) {
      window.navigator.msSaveBlob(blob, fileName + (isArchive ? '.zip' : ''));
    } else {
      const link = document.createElementNS(
        'http://www.w3.org/1999/xhtml',
        'a'
      );
      (link as any).href = URL.createObjectURL(blob);
      (link as any).download = fileName + (isArchive ? '.zip' : '');
      document.body.appendChild(link);
      link.click();
      setTimeout(function () {
          document.body.removeChild(link);
          link.remove();
      }, 100);
   }
}
Run Code Online (Sandbox Code Playgroud)

至此,我成功地从服务器下载了文件。

但是,Chrome 中的下载栏仅在下载完成后才会出现。因此,如果文件太大,用户将不会收到任何指示其文件当前正在下载的指示。

下面是正在下载的 16Mb 文件的屏幕截图。服务器当前正在发送数据,但不出现下载栏。

大小不断增加,但没有进度指示

然后,下载完成后,该文件就会出现在屏幕底部的下载栏中。

该文件显示但仅在最后

如何将文件发送到浏览器,以便它向用户显示该指示器?

非常感谢。

编辑:

正如 @CodeCaster 指出的,重定向到 URL 是可行的,但是,我的 URL 受到保护,因此只有连接的用户才能下载该文件。

Ali*_*bar 2

在 Angular 方面,只需使用锚标记并在属性中传递 API URL href

<a href = {this.apiUrl + '/downloadFile' + '?' + 'your params'}>Download</a>
Run Code Online (Sandbox Code Playgroud)

并且在流数据之前在服务器端,请确保您已设置以下响应标头。

res.setHeader('content-length',data.ContentLength)  (optional)
res.setHeader('content-type', mimetype);
res.setHeader('content-disposition', 'attachment; filename');
Run Code Online (Sandbox Code Playgroud)