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

Blazor JSInterop报错:找不到downloadFile函数(ABP.io项目)

解决方向

1. 修正ES模块的导出逻辑

你通过IJSObjectReference导入的是ES模块,file.js中的downloadFile必须显式导出,否则模块内部的函数无法被外部调用。

修改file.js:

export function downloadFile(fileName, content) {
  // 你的下载逻辑代码
}

如果用默认导出,调用时要对应调整:

export default function downloadFile(fileName, content) {
  // 你的下载逻辑代码
}
// C#调用时改为
await _jsModule.InvokeVoidAsync("default", contentDto.FileName, contentDto.Content);

2. 避免重复加载脚本的冲突

你同时通过BundleContributor将file.js打包到global.js(全局作用域),又通过ES模块导入该文件,这会导致脚本被加载两次,且作用域分离(全局 vs 模块作用域),引发调用问题。二选一即可:

方式A:使用全局脚本(通过BundleContributor)

移除模块导入代码,直接用IJSRuntime调用全局函数:

protected override async Task OnInitializedAsync()
{
    PayStubsList = await AzureService.GetPayStubListAsync();
    await base.OnInitializedAsync();
}

private async Task Download(string name)
{
    var contentDto = await AzureService.GetFileAsync(name);
    try
    {
        await JsRuntime.InvokeVoidAsync("downloadFile", contentDto.FileName, contentDto.Content);
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw new UserFriendlyException($"Error Downloading the File.");
    }
}

方式B:仅使用ES模块导入

从BundleContributor中移除./scripts/file.js的添加,确保脚本只通过模块导入加载,同时保证file.js导出正确、路径无误。

3. 验证模块导入路径的正确性

ABP项目中,wwwroot下的静态资源需要用绝对路径导入,否则相对路径可能基于组件路由路径导致加载错误。修改导入路径:

_jsModule = await JsRuntime.InvokeAsync<IJSObjectReference>("import", "/scripts/file.js");

4. 确认打包后的资源状态

执行abp bundle -f后,检查wwwroot/bundles/global.js是否包含downloadFile代码,同时确保wwwroot/scripts/file.js存在(如果用模块导入)。通过Chrome开发者工具的Sources标签,查看加载的脚本内容,确认函数是否存在于对应作用域中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 12:12:16