1. 程式人生 > 其它 >.Net Core WebAPI + Axios +Vue 實現下載與下載進度條

.Net Core WebAPI + Axios +Vue 實現下載與下載進度條

技術標籤:.NET Core

故事的開始

老闆說:系統很慢,下載半個小時無法下載,是否考慮先壓縮再給使用者下載?

  本來是已經壓縮過了,不過第一反應應該是使用者下的數量多,導致壓縮包很大,然後自己測試發現,只是等待的時間比較久而已,仍然是下載狀態中,並不是系統慢,但是使用者體驗肯定是最直觀的,確實是我們做得不夠好,單純彈出遮罩層顯示冰冷的“拼命載入中……”,對使用者來說確實不夠友好。嗯,瞭解實際情況了,那就開擼,增加使用者體驗。

解決它

效果圖:

Vue+ElementUI

 <el-progress v-if="dlProgress>0" :text-inside="true" :stroke-width="18" :percentage="dlProgress" status="success" style="margin-bottom:10px"></el-progress>

Axios

downloadTask(index,row) {
      let own =this;
      this.fullscreenLoading = true;
      this.axios({
        method: 'post',
        url: this.baseUrl + '/api/Task/DownLoad',
        data: {id: row.id},
        responseType: 'blob',
     //敲黑板
        onDownloadProgress (progress) {
          own.dlProgress=Math.round(progress.loaded / progress.total * 100);
        }
      })
      .then((res) => {
        this.fullscreenLoading = false;
        let fileName = decodeURI(res.headers["content-disposition"].split("=")[1]);
        let url = window.URL.createObjectURL(new Blob([res.data]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
     document.body.removeChild(link); 
        this.$message.success('下載成功');
      })
      .catch(() => {
        this.fullscreenLoading = false;
      });
    },

下載:

 protected IActionResult DownLoad(string fullFilePath)
        {
            var fileName = Path.GetFileName(fullFilePath);
            HttpContext.Response.Headers.Append("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName));

            var contentType = Common.Helper.FileHelper.GetContentType(fileName);
            var stream = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            return File(stream, contentType);
        }

        protected IActionResult DownLoad(VDownloadByte download)
        {
            if (string.IsNullOrEmpty(download.fileName))
                return new JsonResult(ShowError("生成檔案失敗"));
            var fileName = Path.GetFileName(download.fileName);
            HttpContext.Response.Headers.Append("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName)); 
            var contentType = Common.Helper.FileHelper.GetContentType(fileName); 
            return File(download.fileByte, contentType);
        }

        protected IActionResult DownLoad(VDownloadStream download)
        {
            if (string.IsNullOrEmpty(download.fileName))
                return new JsonResult(ShowError("生成檔案失敗"));
            var fileName = Path.GetFileName(download.fileName);
            HttpContext.Response.Headers.Append("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName));
            var contentType = Common.Helper.FileHelper.GetContentType(fileName);
            return File(download.Stream, contentType);
        }


分片下載:

        /// <summary>
        /// 手動分片下載
        /// </summary>
        protected async Task<IActionResult> DownLoadBlock(string fullFilePath)
        {
            var fileName = Path.GetFileName(fullFilePath);
            int bufferSize = 1024;
            Response.ContentType = FileHelper.GetContentType(fileName); 
            Response.Headers.Append("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName));

            using (FileStream fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (Response.Body)
                {
                    long contentLength = fs.Length;
                    Response.ContentLength = contentLength;

                    byte[] buffer;
                    long hasRead = 0;

                    while (hasRead < contentLength)
                    {
                        if (HttpContext.RequestAborted.IsCancellationRequested)
                        {
                            break;
                        }

                        buffer = new byte[bufferSize];
                        int currentRead = fs.Read(buffer, 0, bufferSize);
                        await Response.Body.WriteAsync(buffer, 0, currentRead);
                        await Response.Body.FlushAsync();
                        hasRead += currentRead;
                    }
                }
            }

            return new EmptyResult();
        }