简体   繁体   English

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

[英]Browser doesn't show progress bar when downloading a file

I have an Angular application with an ASP.NET Web API.我有一个带有 ASP.NET Web API 的 Angular 应用程序。

I want to download a file stored on my server.我想下载存储在我的服务器上的文件。 Currently, this is the code I have:目前,这是我的代码:

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

And in my Angular code:在我的 Angular 代码中:

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

With this, I successfully download a file from the server.有了这个,我成功地从服务器下载了一个文件。

However, the download bar in Chrome only appears when the download is done.但是,Chrome 中的下载栏仅在下载完成后才会出现。 So if the file is too big, the user won't get any indicator that his file is currently being downloaded.因此,如果文件太大,用户将不会获得任何指示当前正在下载其文件的指示符。

Below is a screenshot of a 16Mb file being downloaded.下面是正在下载的 16Mb 文件的屏幕截图。 The server is currently sending data but the download bar doesn't appear.服务器当前正在发送数据,但未出现下载栏。

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

Then, once the download has completed, the file appears in the download bar at the bottom of the screen.然后,一旦下载完成,文件就会出现在屏幕底部的下载栏中。

该文件显示,但只在最后

How can I send the file to the browser so that it shows this indicator to the user?如何将文件发送到浏览器,以便向用户显示此指示器?

Thank you very much.非常感谢。

EDIT:编辑:

As @CodeCaster pointed out, redirecting to the URL could work, however, my URL is protected so that only connected users can download the file.正如@CodeCaster 指出的那样,重定向到 URL 是可行的,但是,我的 URL 受到保护,因此只有连接的用户才能下载文件。

On Angular side, just use anchor tag and pass the API URL in href attribute.在 Angular 方面,只需使用锚标记并在href属性中传递 API URL。

<a href = {this.apiUrl + '/downloadFile' + '?' + 'your params'}>Download</a>

and also on server side before streaming data, make sure you have set the following response header.并且在流式传输数据之前的服务器端,请确保您已设置以下响应标头。

res.setHeader('content-length',data.ContentLength)  (optional)
res.setHeader('content-type', mimetype);
res.setHeader('content-disposition', 'attachment; filename');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM