关于前端form提交后端返回文件流触发浏览器下载(并发控制)

前文介绍过这种文件下载方式,它有好处也有不足的地方。好处是可以充分利用浏览器自身的资源调度优势,开发只管提交不用关注下载细节,用户可以在浏览器下载任务中看到下载的状态。不足之处是只能下载到浏览器配置的默认下载位置,而且JS里不能掌握下载状态。

更为关键的是如果一次下载的文件较多的话,提交了N个请求,这样浏览器会创建N个标签页,虽然浏览器自己会调度,下载完后自行关闭这些标签页,但是会带来密集恐惧,那有没有办法控制下浏览器下载的任务数(虽然处于下载中的最多6个任务,但是等待的任务也是任务啊)

既然文件下载提交后,无法从浏览器得到任务下载状态,那么从服务器呢,这个方案是可行的。

前端任务提交后,后端服务器读取本地文件流通过pipeline对接到response,response设置头参数,pipeline完成后回调sse消息发送到前端通知文件下载完成。

javascript 复制代码
app.get('/events', (req,res)=>{
	res.writeHead(200,  { 'Content-Type': 'text/event-stream', 'Connection': 'keep-alive', 'Cache-Control': 'no-cache' });
	res.write(`data: ${JSON.stringify({"msg":"消息服务正常"})}\n\n`);
	let clientid=stringRandom(32, { letters: 'ABCDEF' });
	clients.push({ "clientid":clientid, "uid":req.session.user.userid, "res":res });
	req.on('close', () => { clients = clients.filter(item => (item.clientid != clientid)); });
});

function sendssemsg(jvar)
	clients.forEach(client=>{ if (client.uid==jvar.uid) { client.res.write(`data: ${JSON.stringify(jvar.msg)}\n\n`) } });
}

...
app.post("/getfile",express.urlencoded({ extended: false }),(req,res)=>{
...
	res.set({ "Content-Type": "application/octet-stream",  "Content-Disposition": "attachment;filename* = UTF-8''"+fixedEncodeURIComponent(filename.substr(filename.lastIndexOf("/")+1)),"Content-Length": stats.size });
	pipeline(fs.createReadStream(filepath), res, (err) => { 
		if (err) console.log("下载出错") 
		else sendssemsg({"uid":userid,"msg":filename+" 下载完成"})
		});
	...

通过sse发送下载结果,效率最好

前端收到相应的sse消息,就可以处理下载任务队列操作了

javascript 复制代码
	function downloadfile(filename) {
		let form=$("#formp");
		$("input[name=filename]").attr("value",filename);
		form.submit();
		}
	
	var indownloading=0;
	const evtSource = new EventSource("/events");

	evtSource.addEventListener('message', function(event) {
		//let jvar=JSON.parse(event.data);
		indownloading-=1;
		if (waitinglist.length>0) {
			indownloading+=1;
			downloadfile(waitinglist.shift());
			}
		})

	let indownloading=0;
	let taskLimit=navigator.hardwareConcurrency;
	while ((indownloading<tasklimit)&&(waitinglist.length>0)) {
		indownloading+=1;
		downloadfile(waitinglist.shift());
		}
html 复制代码
<form name="formp" id="formp" action="/getfile" method="post" target="_blank" rel="noopener noreferrer">
<input name="filename" value="">
</form>

这样效果就是下载任务控制在CPU核数,浏览器上看到的下载标签也不会太多,视觉观感上对用户更友好一些。

相关推荐
NAGNIP3 分钟前
Windows命令行代码自动补全详细步骤
后端
追逐时光者1 小时前
精选 8 款 .NET 开源、前后端分离的快速开发框架,提高开发生产效率!
后端·.net
纸上的彩虹1 小时前
半年一百个页面,重构系统也重构了我对前端工作的理解
前端·程序员·架构
be or not to be1 小时前
深入理解 CSS 浮动布局(float)
前端·css
用户47949283569151 小时前
性能提升 4000%!我是如何解决 运营看板 不能跨库&跨库查询慢这个难题的
数据库·后端·postgresql
LYFlied2 小时前
【每日算法】LeetCode 1143. 最长公共子序列
前端·算法·leetcode·职场和发展·动态规划
老华带你飞2 小时前
农产品销售管理|基于java + vue农产品销售管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
小徐_23332 小时前
2025 前端开源三年,npm 发包卡我半天
前端·npm·github
C_心欲无痕2 小时前
vue3 - 类与样式的绑定
javascript·vue.js·vue3
GIS之路3 小时前
GIS 数据转换:使用 GDAL 将 Shp 转换为 GeoJSON 数据
前端