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


故事的開始

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

                     

 

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

 解決它

效果圖:

 

 

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

分片下載:

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

完美~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM