Reputation: 465
I fetch a file from external source, that returns the file in byte array. Now I want to open the file in the browser.
This is what I do:
public async Task OpenFile()
{
[...]
byte[] pdf = externalResource.GetPdf();
Response.Headers.Add("Content-Disposition", "inline;filename=MyFile.pdf");
await Response.Body.WriteAsync(pdf, 0, pdf.Length);
Response.Body.Seek(0, SeekOrigin.Begin);
//await Response.Body.FlushAsync();
return;
}
The first time I call OpenFile, the PDF-file is shown. But if I call OpenFile again or refresh the window, I get an "The PDF-file could not be opened" from the browser (freely translated from danish).
What am I missing? - and is there another (better) approach?
Thanks!
Upvotes: 0
Views: 1333
Reputation: 83
I think you don't need to write Response.Body.Seek section cause after you write any buffer data to response body, actual response is ready for your browser.
byte[] pdf = File.ReadAllBytes("C:/Users/skilic/Desktop/1.pdf");
context.Response.Headers.Add("Content-Disposition", "inline;filename=MyFile.pdf");
await context.Response.Body.WriteAsync(pdf, 0, pdf.Length);
//context.Response.Body.Seek(0, SeekOrigin.Begin);
I test it with just basic dotnet core web app.
Upvotes: 1