故事的开始

老板说:系统很慢,下载半个小时无法下载,是否考虑先压缩再给用户下载?

  本来是已经压缩过了,不过第一反应应该是用户下的数量多,导致压缩包很大,然后自己测试发现,只是等待的时间比较久而已,仍然是下载状态中,并不是系统慢,但是用户体验肯定是最直观的,确实是我们做得不够好,单纯弹出遮罩层显示冰冷的“拼命加载中……”,对用户来说确实不够友好。嗯,了解实际情况了,那就开撸,增加用户体验。

解决它

效果图:

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()
this.$message.success('下载成功');
})
.catch(() => {
this.fullscreenLoading = false;
});
},

下载:

    public static class HttpContextExtension
{
/// <summary>
/// 获取客户Ip
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetClientUserIp(this HttpContext context)
{
var ip = "";
if (context.Request.Headers.ContainsKey("X-Forwarded-For"))
{
ip = context.Request.Headers["X-Forwarded-For"].ToString();
}
if (string.IsNullOrEmpty(ip) && context.Request.Headers.ContainsKey("X-Real-IP"))
{
ip = context.Request.Headers["X-Real-IP"].ToString();
}
if (string.IsNullOrEmpty(ip))
{
ip = context.Connection.RemoteIpAddress.MapToIPv4().ToString();
}
if (string.IsNullOrEmpty(ip))
return ip;
var sp = ip.RemoveSpacing().Split(',');
return sp[];
} /// <summary>
/// 通过文件流下载文件
/// </summary>
/// <param name="context"></param>
/// <param name="filePath">文件完整路径</param>
/// <param name="contentType">访问这里 https://tool.oschina.net/commons </param>
public static void DownLoadFile(this HttpContext context,string filePath, string contentType= "application/octet-stream")
{
var fileName = Path.GetFileName(filePath); int bufferSize = ;
context.Response.ContentType = contentType;
context.Response.Headers.Append("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
context.Response.Headers.Append("Charset", "utf-8");
context.Response.Headers.Append("Access-Control-Expose-Headers", "Content-Disposition");
//context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
//使用FileStream开始循环读取要下载文件的内容
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (context.Response.Body)
{
long contentLength = fs.Length;
context.Response.ContentLength = contentLength; byte[] buffer;
long hasRead = ;
while (hasRead < contentLength)
{
if (context.RequestAborted.IsCancellationRequested)
{
break;
} buffer = new byte[bufferSize];
//从下载文件中读取bufferSize(1024字节)大小的内容到服务器内存中
int currentRead = fs.Read(buffer, , bufferSize);
context.Response.Body.Write(buffer, , currentRead);
context.Response.Body.Flush();
hasRead += currentRead;
}
context.Response.Body.Close();
}
fs.Close();
}
} /// <summary>
/// 通过文件流下载文件
/// </summary>
/// <param name="context"></param>
/// <param name="filePath">文件完整路径</param>
/// <param name="contentType">访问这里 https://tool.oschina.net/commons </param>
public static void DownLoadFile(this HttpContext context,string fileName, byte[] fileByte, string contentType = "application/octet-stream")
{
int bufferSize = ; context.Response.ContentType = contentType;
context.Response.Headers.Append("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
context.Response.Headers.Append("Charset", "utf-8");
context.Response.Headers.Append("Access-Control-Expose-Headers", "Content-Disposition"); //context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
//使用FileStream开始循环读取要下载文件的内容
using (Stream fs = new MemoryStream(fileByte))
{
using (context.Response.Body)
{
long contentLength = fs.Length;
context.Response.ContentLength = contentLength; byte[] buffer;
long hasRead = ;
while (hasRead < contentLength)
{
if (context.RequestAborted.IsCancellationRequested)
{
break;
} buffer = new byte[bufferSize];
//从下载文件中读取bufferSize(1024字节)大小的内容到服务器内存中
int currentRead = fs.Read(buffer, , bufferSize);
context.Response.Body.Write(buffer, , currentRead);
context.Response.Body.Flush();
hasRead += currentRead;
}
}
}
}
}

完美~

.Net Core WebAPI + Axios +Vue 实现下载与下载进度条的更多相关文章

  1. android AsyncTask异步下载并更新进度条

    AsyncTask异步下载并更新进度条    //如果不是很明白请看上篇文章的异步下载 AsyncTask<String, Integer, String> 第一个参数:String 传入 ...

  2. VC下载文件显示进度条

    VC下载文件显示进度条 逗比汪星人2009-09-18上传   by Koma http://blog.csd.net/wangningyu http://download.csdn.net/deta ...

  3. 【转】C#中使用aria2c进行下载并显示进度条

    [转自] C#中使用aria2c进行下载并显示进度条 - 云平台知识库 - 博客园https://www.cnblogs.com/littlehb/p/5782714.html 正则表达式的生成网站: ...

  4. vue+element UI + axios封装文件上传及进度条组件

    1.前言 之前在做项目的时候,需要实现一个文件上传组件并且需要有文件上传进度条,现将之前的实现过程简单记录一下,希望可以帮助到有需要的人. 项目用的是Vue框架,UI库使用的是element UI,前 ...

  5. Vue中使用NProgress实现进度条

    简介 NProgress是页面跳转或者发生异步请求是浏览器顶部的进度条 GitHub地址:https://github.com/rstacruz/nprogress 在线演示地址:http://ric ...

  6. VC下载文件 + 显示进度条

    在codeproject里找了许久,发现这样一个VC下载文件并显示进度条的源码,于是添加了些中文注释: 1.下载线程函数: UINT DownloadFile(LPVOID pParam) { CWn ...

  7. idhttp post 上传或下载时显示进度条

    通过 idhttp 带进度条上传演示一下,下载和上传原理差不多,说明一下下面例子中的的idhttp 是动态创建的 第一步:添加一个StatusBar或者gauge 进度条,这2个都可以.我用的是 st ...

  8. webclient下载文件 带进度条

    private void button1_Click(object sender, EventArgs e) { doDownload(textBox1.Text.Trim()); } private ...

  9. Android开发(24)---安卓中实现多线程下载(带进度条和百分比)

    当我们学完java中多线程的下载后,可以将它移植到我们的安卓中来,下面是具体实现源码: DownActivity.java package com.example.downloads; import ...

随机推荐

  1. pyppteer下

    目录 启动pyppteer 切图 获取响应头,响应头状态,cookies 获取当前页面标题 获取页面html 第一种:获取整个页面html 第二种:只获取文本 注入JS,控制上下滚动 选择器 获取元素 ...

  2. Spring初学笔记(一):Spring IOC的理解

    关于依赖注入.控制反转 Ioc—Inversion of Control,即“控制反转”,不是什么技术,而是一种设计思想.在Java开发中,Ioc意味着将你设计好的对象交给容器控制,而不是传统的在你的 ...

  3. [Unity3D]编辑器扩展之数组或List显示

    效果如下: 源码如下: using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace XM.Edi ...

  4. flask之CORS跨域请求处理

    from flask import Flask from flask_cors import CORS#pip install Flask-CORS#跨域请求模块 app = Flask(__name ...

  5. 201771010128王玉兰《面向对象与程序设计(java)第十五周学习总结》

    第一部分:理论知识 一:JAR文件 Java程序的打包:程序编译完成后,程序员 将.class文件压缩打包为.jar文件后,GUI界面 程序就可以直接双击图标运行. jar文件(Java归档)既可以包 ...

  6. MySQL(6)— 事务

    六.事务 ACID: 原子性.一致性.隔离性和持久性 原子性(atomicity) :一组事务,不能再细分了,其中的sql, 要么全部提交成功,要么全部失败回滚,不能只提交其中的一部分操作. 一致性( ...

  7. 【python爬虫】scrapy入门4--添加cookies

    (1) settings.py 取消注释:COOKIES_ENABLED = True (2)爬虫xx.py def parse(self, response): c_dic = {自己抓包} # 获 ...

  8. fastclick从接触到丢弃

    fastclick简介 fastclick是一款为了解决移动端300ms点击延迟而诞生的插件. 在移动端,如果对页面没有做任何处理,点击一个元素,触发的事件流程可简单理解为:touch -> 经 ...

  9. [Python基础]001.Python准备

    Python准备 Python简介 使用版本 环境安装 编写第一个Python文件 编辑器选择 Python简介 Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,能简单而有效 ...

  10. Spring_AOP_AspectJ支持的通知注解

    1.AOP前奏: 使用动态代理解决日志需求 ArithmeticCalculator.java package com.aff.spring.aop.helloworld; public interf ...