.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()
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 实现下载与下载进度条的更多相关文章
- android AsyncTask异步下载并更新进度条
AsyncTask异步下载并更新进度条 //如果不是很明白请看上篇文章的异步下载 AsyncTask<String, Integer, String> 第一个参数:String 传入 ...
- VC下载文件显示进度条
VC下载文件显示进度条 逗比汪星人2009-09-18上传 by Koma http://blog.csd.net/wangningyu http://download.csdn.net/deta ...
- 【转】C#中使用aria2c进行下载并显示进度条
[转自] C#中使用aria2c进行下载并显示进度条 - 云平台知识库 - 博客园https://www.cnblogs.com/littlehb/p/5782714.html 正则表达式的生成网站: ...
- vue+element UI + axios封装文件上传及进度条组件
1.前言 之前在做项目的时候,需要实现一个文件上传组件并且需要有文件上传进度条,现将之前的实现过程简单记录一下,希望可以帮助到有需要的人. 项目用的是Vue框架,UI库使用的是element UI,前 ...
- Vue中使用NProgress实现进度条
简介 NProgress是页面跳转或者发生异步请求是浏览器顶部的进度条 GitHub地址:https://github.com/rstacruz/nprogress 在线演示地址:http://ric ...
- VC下载文件 + 显示进度条
在codeproject里找了许久,发现这样一个VC下载文件并显示进度条的源码,于是添加了些中文注释: 1.下载线程函数: UINT DownloadFile(LPVOID pParam) { CWn ...
- idhttp post 上传或下载时显示进度条
通过 idhttp 带进度条上传演示一下,下载和上传原理差不多,说明一下下面例子中的的idhttp 是动态创建的 第一步:添加一个StatusBar或者gauge 进度条,这2个都可以.我用的是 st ...
- webclient下载文件 带进度条
private void button1_Click(object sender, EventArgs e) { doDownload(textBox1.Text.Trim()); } private ...
- Android开发(24)---安卓中实现多线程下载(带进度条和百分比)
当我们学完java中多线程的下载后,可以将它移植到我们的安卓中来,下面是具体实现源码: DownActivity.java package com.example.downloads; import ...
随机推荐
- ql的python学习之路-day1
写在前面的话:万事开头难,算是系统学习python的一个月了吧,总该写点什么来记录一下,之前看老男孩day1的视频没有开通博客,这次给补上,对于学python还是要好好努力,不能半途而废,还是那句老话 ...
- 【雕爷学编程】Arduino动手做(47)---七段LED数码管模块
37款传感器与模块的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止37种的.鉴于本人手头积累了一些传感器和模块,依照实践(动手试试)出真知的理念,以学习和交流为目的,这里准备 ...
- 「雕爷学编程」Arduino动手做(8)——湿度传感器模块
37款传感器和模块的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止37种的.鉴于本人手头积累了一些传感器与模块,依照实践出真知(动手试试)的理念,以学习和交流为目的,这里准备 ...
- Codeforces1144C(C题)Two Shuffled Sequences
C. Two Shuffled Sequences Two integer sequences existed initially — one of them was strictly increas ...
- Adaboost原理及相关推导
提升思想 一个概念如果存在一个多项式的学习算法能够学习它,并且正确率很高,那么,这个概率是强可学习的.一个概念如果存在一个多项式的学习算法能够学习它,并且学习的正确率仅比随机猜测略好,那么,这个概念是 ...
- zz 通过INFORMATION_SCHEMA.INNODB_TRX、INNODB_LOCKS、INNODB_LOCK_WAITS 三个表获取事务与锁的信息
zz from http://imysql.com/2015/03/25/mysql-faq-how-to-fetch-latest-trxid.shtml #先查询 INNODB_TRX 表,看看都 ...
- ol,li,ul,dl,dt,dd
块级元素div尽量少用,其实和table一样,嵌套越少越好,它也是会影响速度的! ol 有序列表. <ol> <li>……</li> <li>……< ...
- Web-Security-Learning
Web Security sql注入 MySql MySQL False 注入及技巧总结 MySQL 注入攻击与防御 sql注入学习总结 SQL注入防御与绕过的几种姿势 MySQL偏门技巧 mysql ...
- php 序列化
PHP serialize() 函数 serialize() 函数用于序列化对象或数组,并返回一个字符串. serialize() 函数序列化对象后,可以很方便的将它传递给其他需要它的地方,且其类型和 ...
- [Android应用开发] 05.广播和服务
*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...