我正试图从blazor下载一个PDF文件,该文件由我的WebAPI以byte[](byteArray(的形式发送。我知道我的PDF正在工作,因为当我将其作为filestreamResult发送并直接从我的WebAPI中检索(例如使用swagger(时,我会得到正确的PDF文件。
我的WebAPI:
var response = await GetResponse(new Query(request.AnalysisDate), ct);
string html = await _templateService.PerformanceReport(response);
MemoryStream stream = _pdfService.GeneratePdf(html);
return await stream.ToArray(); // as byte[]
Blazor侧:
var bytes = await _http.GetByteArrayAsync(endpoint);
await JsRuntime.InvokeVoidAsync("BlazorDownloadFile", "file.pdf", "application/pdf", bytes);
JS:
function BlazorDownloadFile(filename, contentType, content) {
// Create the URL
const file = new File([content], filename, { type: contentType });
const exportUrl = URL.createObjectURL(file);
// Create the <a> element and click on it
const a = document.createElement("a");
document.body.appendChild(a);
a.href = exportUrl;
a.download = filename;
a.target = "_self";
a.click();
// We don't need to keep the object url, let's release the memory
// On Safari it seems you need to comment this line... (please let me know if you know why)
URL.revokeObjectURL(exportUrl);
}
我正确下载了一个名为file.PDF的PDF文件,但它看起来已经损坏。
这是.NET 6的正确方法吗?
我应该从Web API发送FileStreamResult吗(我喜欢我可以直接从swagger获取文件的事实(?
在如何做到这一点上,我真的找不到一个好的例子给blazor。如有任何帮助,我们将不胜感激。
我正在使用另一种方法。我发送base64String。我将字节数组转换为base64字符串,然后将字符串传递给javascript函数
服务器端呼叫:
js.InvokeVoidAsync("jsSaveAsFile",
filename,
Convert.ToBase64String(GetFileByteArrayFunction())
);
javascript函数:
function jsSaveAsFile(filename, byteBase64) {
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + byteBase64;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);}
js->使用Microsoft.JSInterop.
您应该这样发送文件:
app.MapGet("/download", () =>
{
//...
Results.File("myfile.pdf");
});
这个方法有一些重载,你可以选择一个符合你要求的方法。