You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor 6.0 WebAssembly报错:downloadFileFromStream未定义

解决Blazor WebAssembly中downloadFileFromStream未定义的问题

排查及修复步骤

  • 确认脚本加载顺序与位置
    确保自定义脚本放在blazor.webassembly.js之后,且位于body标签内部(推荐放在</body>闭合标签前),保证Blazor初始化前全局函数已注册:

    <body>
      <div id="app">Loading...</div>
    
      <script src="_framework/blazor.webassembly.js"></script>
      <script>
        window.downloadFileFromStream = async (fileName, contentStreamReference) => {
          const arrayBuffer = await contentStreamReference.arrayBuffer();
          const blob = new Blob([arrayBuffer]);
          const url = URL.createObjectURL(blob);
          const anchorElement = document.createElement('a');
          anchorElement.href = url;
          anchorElement.download = fileName ?? '';
          anchorElement.click();
          anchorElement.remove();
          URL.revokeObjectURL(url);
        }
      </script>
    </body>
    
  • 清除浏览器缓存
    旧的index.html缓存可能导致新脚本未加载,按下Ctrl+F5强制刷新页面,或在浏览器开发者工具中勾选"Disable cache"选项禁用缓存。

  • 验证脚本执行状态
    在自定义脚本中添加日志输出,确认函数是否成功注册:

    <script>
      console.log('Registering downloadFileFromStream');
      window.downloadFileFromStream = async (fileName, contentStreamReference) => {
        // 原函数代码
      }
    </script>
    

    打开浏览器控制台(F12),查看是否输出Registering downloadFileFromStream,以此确认脚本是否被正确加载执行。

  • 调整JS函数调用时机
    避免在组件的OnInitializedAsync生命周期中调用该函数(此时Blazor与JS的绑定可能未完成),建议在用户交互事件(如按钮点击)或OnAfterRenderAsync中触发下载:

    <button @onclick="TriggerDownload">下载文件</button>
    
    @code {
      private async Task TriggerDownload()
      {
          // 此处获取fileName和streamRef
          await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
      }
    }
    
  • 排查全局函数覆盖问题
    检查项目中其他JS脚本,确认没有其他代码覆盖window.downloadFileFromStream函数,避免命名冲突。

内容的提问来源于stack exchange,提问作者Christian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:30:53