.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 ...
随机推荐
- axios请求拦截器(修改Data上的参数 ==>把data上的参数转为FormData)
let instance = axios.create({ baseURL: 'http://msmtest.ishare-go.com', //请求基地址 // timeout: 3000,//请求 ...
- 3.2 Go整数类型
1. Go整数类型 Go语言的数值类型包含不同大小的整数型.浮点数和负数,每种数值类型都有大小范围以及正负符号. 官方文档解释数据类型 int类型中哪些支持负数 有符号(负号):int8 int16 ...
- React安装及使用
学习React之前.你可能需要学习: Html5.Css3.React.Antd.js. Html5的学习网站:http://www.w3school.com.cn/ Css3学习网站:http:// ...
- 猜想-未做 利用office组件读取excel数据
---未实际使用过 用SQL-Server访问Office的Access和Excel http://blog.sina.com.cn/s/blog_964237ea0101532x.html 2007 ...
- SpringAOP注解报错:java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut selectAll
原因 我使用的aspectjweaver.jar版本是1.5.1,版本过低,导致报错. 需要下载高本版的aspectjweaver.jar. 解决办法 在这里下载:https://mvnreposit ...
- poi--读取不同类型的excel表格
要想根据不同类型excel表格获取其数据,就要先判断其表格类型 poi-api种方法: getCellType public int getCellType() Return th ...
- 替换Java WEB工程文件的指定字符串
package com.utils; import java.io.BufferedReader;import java.io.File;import java.io.FileFilter;impor ...
- Linux(一):VMware安装出现的问题
目录 1 兼容性问题 2 VMware打卡虚拟机提示"此虚拟机可能已被复制或移动" 1 兼容性问题 问题:VMware Workstation 与 Device/Credentia ...
- IT笑话十则(二)
一.女程序员征婚 女程序员是这么征婚的: SELECT * FROM 男人们 WHERE 未婚=true and 同性恋=false and 有房=true and 有车=true and 条件 in ...
- 数据库原理实验指导(三)使用SQL语言进行简单查询【转载csdn】
--1.查询全体学生的学号和姓名select sno,sname from student --2.查询全体学生的详细记录select * from student --3.查询软件学院的学生姓名,年 ...