Issue with saving files into SQL as varbinary(max)

281 Views Asked by At

So, I have a web application that saves some attachments into SQL database as VarBinary(max), everything working smoothly until I realized that when I download the attachment from the database, the file is very big comparing to the original size, so a file with 400KB, the downloaded one would be 5MB! what I'm doing wrong?

The upload code is:

Dim img As FileUpload = CType(FileUpload1, FileUpload)
Dim imgByte As Byte() = Nothing
If img.HasFile AndAlso Not img.PostedFile Is Nothing Then
    Dim File As HttpPostedFile = FileUpload1.PostedFile
    imgByte = New Byte(File.ContentLength - 1) {}
    File.InputStream.Read(imgByte, 0, File.ContentLength)
    cmd.Parameters.AddWithValue("@filetype", Path.GetExtension(FileUpload1.FileName).ToLower)
    cmd.Parameters.AddWithValue("@attachment", imgByte)
End If

The download code:

Dim imagem As Byte() = CType((dr("attachment")), Byte())
Response.Clear()
Response.AddHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0")
Response.AddHeader("Pragma", "no-cache")
Response.AddHeader("Content-Description", "File Download")
Response.AddHeader("Content-Type", "application/force-download")
Response.AddHeader("Content-Transfer-Encoding", "binary\n")
Dim fileName As String = "attachment; filename=" & "DOC_REFNO_" & "_" & regref_txt.Text.Replace("/", "_") & dr("filetype")
Response.AddHeader("content-disposition", fileName)
Response.BinaryWrite(imagem)

Thank you all.

1

There are 1 best solutions below

1
Osama Gadour On

so I found out that the download code is not correct, I changed it to the following code and worked perfectly.

 Dim imagem As Byte() = CType((dr("attachment")), Byte())
            Response.Buffer = True
            Response.Charset = ""
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.ContentType = ContentType
            Dim fileName As String = "attachment; filename=" & "DOC_REFNO_" & "_" & regref_txt.Text.Replace("/", "_") & dr("filetype")

            Response.AddHeader("content-disposition", fileName)
            Response.BinaryWrite(imagem)
            Response.Flush()
            Response.End()