I am unable to stream a word document that I create on the fly down to the browser. I am constantly getting a message from Microsoft Word that the document is corrupt.
First of all, always include Content-Length. If browser does not know the length of the http response body, then the connection remains opened (keep-alive). If there is no other way, save content to temp file (with delete on close option), and then get the content length.
Second, the document processing IN-MEM does not work for all options (for example, you cannot insert chunk into the document. You must use file mode).
Below is the sample for aspnet core :
[HttpPost]
public async Task<ActionResult<MopedResponse>> PostAsync(IFormCollection collection)
{
string pathTemp = Path.GetTempFileName(); // get the temp file name
// create or process the word file
// reopen it for serving
FileStream merged = new FileStream(pathTemp, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose);
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
FileName = "parafa.docx",
Inline = true // false = prompt the user for downloading; true = browser to try to show the file inline
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("Content-Length", merged.Length.ToString());
return File(merged, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "mywordFile1.docx");
}