Streaming In Memory Word Document using OpenXML SDK w/ASP.NET results in “corrupt” document

前端 未结 7 567
北恋
北恋 2021-01-01 15:01

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.

相关标签:
7条回答
  • 2021-01-01 15:44

    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");
    
    }
    
    0 讨论(0)
提交回复
热议问题