Controller Action执行文件下载生成操作时如何显示忙状态指示器
解决方案
1 前端视图修改
替换原有a标签代码,新增加载状态元素和交互逻辑:
<!-- 下载按钮,移除原有href跳转逻辑 --> <a href="javascript:void(0)" id="downloadAnalysisBtn" title="Get analysis file"> <span class="fa fa-bar-chart"></span> </a> <!-- 加载指示器,默认隐藏 --> <span id="downloadLoading" style="display:none; margin-left:8px;"> 正在生成文件,请稍候... <span class="fa fa-spinner fa-spin"></span> </span> <script> document.getElementById('downloadAnalysisBtn').addEventListener('click', function() { const loadingEl = document.getElementById('downloadLoading'); // 点击后立刻显示加载状态 loadingEl.style.display = 'inline-block'; fetch('@Url.Action("DownloadAnalysis", "Analysis")') .then(response => { if (!response.ok) throw new Error('文件生成失败'); // 从响应头提取文件名 const contentDisposition = response.headers.get('Content-Disposition'); const fileName = contentDisposition ? contentDisposition.match(/filename="?([^"]+)"?/)?.[1] : 'analysis.csv'; return Promise.all([response.blob(), Promise.resolve(fileName)]); }) .then(([blob, fileName]) => { // 前端模拟触发下载 const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); }) .catch(err => { alert(err.message); }) .finally(() => { // 无论请求成功/失败,都隐藏加载状态 loadingEl.style.display = 'none'; }); }); </script>
2 Controller代码优化
原有逻辑不需要大改,仅将返回null的分支替换为规范的错误响应即可:
public ActionResult DownloadAnalysis() { var response = StartAnalysis(); if (response.AnalysisByteArray != null && response.AnalysisByteArray.Length > 0) { var cd = new System.Net.Mime.ContentDisposition { FileName = response.FileName, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(response.AnalysisByteArray , "text/csv"); } // 替换原有的return null return HttpNotFound("无可用分析文件"); }
实现说明
原有的a标签同步跳转无法监听请求生命周期,改用fetch异步请求可以完整捕获请求的开始、结束、异常状态,不需要修改服务端文件生成逻辑,也不需要将文件落地到服务器硬盘,下载效果和原有同步方案完全一致。
内容的提问来源于stack exchange,提问作者Bati_84
相关产品推荐
相关产品推荐

