I'm trying to download a PDF file from blazor sent by my WebAPI as byte[] (byteArray). I know that my PDF is working because when I send it as filestreamResult and retrieve it directly from my WebAPI (using swagger for example), I get the correct PDF file.
My 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 Side:
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);
}
I Correctly download a PDF file named file.pdf but it looks corrupted.
Is this the correct approach with .NET 6?
Should I send a FileStreamResult from the Web API (I Like the fact that I can get the file directly from swagger)?
I can't really find a good example for blazor on how to do this. Any help would be appreciated.
CodePudding user response:
I am using another aproach. I send base64String. I convert byte array to base64 string then i pass the string to javascript function
Server side call:
js.InvokeVoidAsync("jsSaveAsFile",
filename,
Convert.ToBase64String(GetFileByteArrayFunction())
);
javascript function:
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 -> using Microsoft.JSInterop.
CodePudding user response:
You should send your file like this:
app.MapGet("/download", () =>
{
//...
Results.File("myfile.pdf");
});
there are some overloads of this method you can pick up the one that fit your requirements.