我按照这个视频中的说明:https://www.youtube.com/watch?v=7V0Yb5drLgQ
链接时直接进入我的剃刀组件html部分一切正常:
RazorComponent
<a type="button" style="margin-left:20px;" class="btn btn-outline-secondary" href="https://localhost:5001/api/Report/GetReport?reportType=1">
<span class="oi oi-data-transfer-download"></span> @(l.Keys["CPVH_Download_PDF"])
</a>
</div>
下面是我的API的控制器逻辑
<<p>服务器Api/strong>[HttpGet("[action]/{reportType}")]
public IActionResult GetReport(int reportType)
{
var dt = new DataTable();
dt = employeeService.GetEmployee();
string mimeType = "";
int extension = 1;
var path = $"{this._webHostEnvironment.WebRootPath}\Reports\Report1.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("param", "RDLC report in Blazor Web Assembly");
LocalReport localReport = new LocalReport(path);
localReport.AddDataSource("dsEmployee", dt);
//For Pdf
if (reportType == 1)
{
var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimeType);
return File(result.MainStream, "application/pdf", "myPdf.pdf");
}
else //if (reportType == 1)
{
//For Excel
var result = localReport.Execute(RenderType.Excel, extension, parameters, mimeType);
return File(result.MainStream, "application/msexcel", "myReport.xls");
}
}
然而,当我将razor组件调用封装到调用Get或Post的服务中时,即使我仍然点击了控制器,文件也没有被下载。我只得到一个Ok的响应,但没有文件下载。
Service调用api
public async Task GetReport(int reportType)
{
var httpResponse = await _httpClient.GetAsync($"{_httpClient.BaseAddress.ToString()}/Report/GetReport/{reportType}");
var saveDir = Path.Combine(Path.GetTempPath(), "myPdf.pdf");
if (httpResponse.IsSuccessStatusCode)
{
var content = httpResponse.Content.ReadAsByteArrayAsync().Result;
File.WriteAllBytes(saveDir, content);
}
}
我找到了如何使用第三方扩展来解决这个问题:https://github.com/arivera12/BlazorDownloadFile
_iBlazorDownloadFileService。DownloadFile获取fileBytes并将其转换为保存在Downloads文件夹中的文件。
这里是我的实现
public async Task<byte[]> GetReport(int reportType)
{
var httpResponse = await _httpClient.GetAsync($"{_httpClient.BaseAddress.ToString()}/Report/GetReport/{reportType}");
byte[] content = null;
if (httpResponse.IsSuccessStatusCode)
content = httpResponse.Content.ReadAsByteArrayAsync().Result;
return content;
}
Razor.component
@inject IExportService _iExportService
@inject IBlazorDownloadFileService _iBlazorDownloadFileService
<a style="margin-left:20px;" class="btn btn-outline-secondary" @onclick="@(async ()=> await GetExport((int)ExportTypesEnum.Pdf))" >
<span class="oi oi-data-transfer-download"></span> @(l.Keys["CPVH_Download_PDF"])
</a>
@code {
public async Task GetExport(int reportType)
{
var fileBytes = await _iExportService.GetReport(reportType);
await _iBlazorDownloadFileService.DownloadFile("myPdf.pdf", fileBytes, "application/pdf");
}
}