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

使用ABP.IO Blazor WASM从Azure Blob下载文件遇404及JS问题

问题修复方案

1. 解决JSInterop找不到download方法的问题

核心原因是你通过ES模块导入了JS函数,但仍在调用全局download方法,需改为通过导入的模块调用,并确保参数结构匹配。

修改Files.razor.cs:

// 添加模块声明
private IJSObjectReference _jsModule;

protected override async Task OnInitializedAsync()
{
    _jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./scripts/file.js");
    await base.OnInitializedAsync();
}

private async Task Download(string name, string contentType)
{
    try
    {
        var contentDto = await _fileService.GetBlobAsync(name); 

        // 通过导入的JS模块调用download,传递匹配的参数对象
        await _jsModule.InvokeVoidAsync("download", new {
            fileName = contentDto.Name,
            byteArray = contentDto.Content,
            contentType = contentDto.ContentType
        });
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

// 组件销毁时释放JS模块
public async ValueTask DisposeAsync()
{
    if (_jsModule != null)
    {
        await _jsModule.DisposeAsync();
    }
}

2. 解决UI端下载404错误

核心原因是ABP远程服务代理的默认路由与你的API路由不匹配,Swagger能识别[HttpGet("{name}")]路由,但ABP代理默认按方法名生成请求路径。

方案A:调整API路由适配ABP代理
修改API控制器的Get方法,改用查询参数:

[HttpGet]
public async Task<IActionResult> Get([FromQuery] string name)
{
    var result = await _fileService.GetBlobAsync(Uri.UnescapeDataString(name));
    return File(result.Content, result.ContentType, result.Name);
}

方案B:在应用服务接口指定路由
为IFileService接口添加路由特性,让ABP代理生成正确的请求路径:

[RemoteService(Name = "Files")]
public interface IFileService : IApplicationService
{
    [HttpGet("{name}")]
    Task<ContentDto> GetBlobAsync(string name);
}

额外处理:文件名编码
若文件名包含特殊字符(空格、中文等),需确保传递时编码正确:

  • Blazor端调用:await _fileService.GetBlobAsync(Uri.EscapeDataString(name));
  • API端接收:var result = await _fileService.GetBlobAsync(Uri.UnescapeDataString(name));

3. 验证JS函数参数匹配

当前file.js的参数结构已与Blazor传递的对象匹配,无需修改:

export function download(options) {
    var bytes = new Uint8Array(options.byteArray);
    var blob=new Blob([bytes], {type: options.contentType});

    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download=options.fileName;
    link.click();
    link.remove();
    window.URL.revokeObjectURL(link.href);
}

内容的提问来源于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.28 12:50:18