使用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
相关产品推荐
相关产品推荐

