.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 ...
随机推荐
- sound of the genuine
“There is something in every one of you that waits and listens for the sound of the genuine in yours ...
- Java线程的几种可用状态
1. 新建( new ):新创建了一个线程对象. 2. 可运行( runnable ):线程对象创建后,其他线程(比如 main 线程)调用了该对象 的 start()方法.该状态的线程位于可运行线程 ...
- Linux内存屏障浅析
根据该文章整理 https://blog.csdn.net/myxmu/article/details/8035025 1 解决的问题 内存屏障主要解决了单处理器下的乱序问题和多处理器下的内存同步问题 ...
- COCO数据集提取特定多个类并在YOLO-V3上训练
先占个地方,有空再写 ` import os Dir = './coco_class_6/Annotations/val2014' ImageDir = './coco_class_6/images/ ...
- Poj2109 (2) k^n = p.
二分法,由p最大值最小值的中间值开始猜k,通过比较pow(k,n)与p的大小来进一步精确k,直到找到. #include<stdio.h> #include<math.h> # ...
- docker 日志查看与清洗
Linux下查看磁盘与目录的容量——df.du df:列出文件系统的整体磁盘使用量: du:评估文件系统的磁盘使用量(常用于评估目录所占容量) df参数: -a:列出所有的文件系统,包括系统特有的/p ...
- JSP学习之请求和响应编码
今天的学习涉及到了 jsp中的两大函数 request(请求) 和 response(响应),这应该是大家学习jsp时最先碰到的两个对象,具体有什么作用呢?应该怎么用呢?请继续往下面看. 一.requ ...
- Spring_管理bean的生命周期
Spring IOC 容器对 Bean 的生命周期进行管理的过程:通过构造器或工厂方法创建 Bean 实例为 Bean 的属性设置值和对其他 Bean 的引用将 Bean 实例传递给 Bean 后置处 ...
- java基础-HelloWorld
public class HelloWorld{//源文件中只能有一类声明为public , 且类名和源文件名得一样 //main方法,程序的入口 public static void main(St ...
- C#线程 基本同步
第二部分: 基本同步 同步要点 到目前为止,我们已经描述了如何在线程上启动任务,配置线程以及双向传递数据.我们还描述了局部变量如何专用于线程,以及如何在线程之间共享引用,从而允许它们通过公共字段进行 ...