You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将文件以varbinary(max)存入SQL后下载体积异常变大问题咨询

问题根因与修复方案

核心问题

  • 下载时未终止响应:调用Response.BinaryWrite后没有停止当前响应输出,ASP.NET会把页面后续渲染的所有HTML、视图状态等冗余内容追加到二进制文件末尾,是文件体积异常变大的最主要原因。
  • 响应头格式错误:Content-Transfer-Encoding头值多写了\n换行符,会额外输出无效字符到文件中。
  • 上传读取逻辑不严谨:InputStream.Read方法不保证一次性读满指定长度的字节,未处理返回值的情况下,可能出现字节数组后半段用默认0值填充,导致存入数据库的文件本身就大于原始文件。

修复代码

上传代码优化

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) {}
    ' 循环读取直到填充满整个字节数组
    Dim offset As Integer = 0
    Dim remaining As Integer = File.ContentLength
    While remaining > 0
        Dim read As Integer = File.InputStream.Read(imgByte, offset, remaining)
        If read = 0 Then Exit While ' 流提前结束,可根据需要加异常处理
        offset += read
        remaining -= read
    End While
    cmd.Parameters.AddWithValue("@filetype", Path.GetExtension(FileUpload1.FileName).ToLower)
    cmd.Parameters.AddWithValue("@attachment", imgByte)
End If

下载代码修复

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")
' 移除头值里的换行符,也可以直接删除这行,HTTP/1.1不需要这个头
Response.AddHeader("Content-Transfer-Encoding", "binary")
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()

内容的提问来源于stack exchange,提问作者Osama Gadour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:42:00