Why are .docx files being corrupted when downloading from an ASP.NET page?

前端 未结 8 940
长发绾君心
长发绾君心 2020-12-03 05:09

I have this following code for bringing page attachments to the user:

private void GetFile(string package, string filename)
{
    var stream = new MemoryStre         


        
相关标签:
8条回答
  • 2020-12-03 05:37

    For what it's worth, I also ran into the same problem listed here. For me the issue was actually with the upload code not the download code:

        Public Sub ImportStream(FileStream As Stream)
            'Use this method with FileUpload.PostedFile.InputStream as a parameter, for example.
            Dim arrBuffer(FileStream.Length) As Byte
            FileStream.Seek(0, SeekOrigin.Begin)
            FileStream.Read(arrBuffer, 0, FileStream.Length)
            Me.FileImage = arrBuffer
        End Sub
    

    In this example the problem is I declare the Byte array arrBuffer with a size one byte too large. This null byte is then saved with the file image to the DB and reproduced on download. The corrected code would be:

            Dim arrBuffer(FileStream.Length - 1) As Byte
    

    Also for reference my HttpResponse code is as follows:

                    context.Response.Clear()
                    context.Response.ClearHeaders()
                    'SetContentType() is a function which looks up the correct mime type
                    'and also adds and informational header about the lookup process...
                    context.Response.ContentType = SetContentType(objPostedFile.FileName, context.Response)
                    context.Response.AddHeader("content-disposition", "attachment;filename=" & HttpUtility.UrlPathEncode(objPostedFile.FileName))
                    'For reference: Public Property FileImage As Byte()
                    context.Response.BinaryWrite(objPostedFile.FileImage)
                    context.Response.Flush()
    
    0 讨论(0)
  • 2020-12-03 05:38

    It all looks ok. My only idea is to try calling Dispose on your stream after calling Response.Flush instead of before, just in case the bytes aren't entirely written before flushing.

    0 讨论(0)
提交回复
热议问题