代码之家  ›  专栏  ›  技术社区  ›  Clinton Pierce

下载链接未返回正确的字节流

  •  0
  • Clinton Pierce  · 技术社区  · 15 年前

    我正在从数据库服务器检索一个文件,并允许用户下载它。问题是,我没有从服务器读取相同的字节流。

    我已经确认(通过大量的response.write)我收到了正确的字节数组,它们的顺序正确,等等。。。

    下面是下载的代码。文件内容是一个字节[]:

            Response.Clear();
            Response.AddHeader("Content-Disposition", 
                   "attachment; filename=" + st.FileName);
            Response.AddHeader("Content-Length", st.FileSize.ToString());
            Response.ContentType = "application/octet-stream";
            Response.Write(new System.Text.ASCIIEncoding()
                    .GetString(st.FileContents));  // Problem line
            Response.End();
    

    FF D8 FF E0 1E D0 4A 46 58 58 00 10 FF D8 FF DB

    (是的,这是jpeg图像的开始)

    我最终得到了这样的结果:

    C3 BF C3 98 C3 BF C3 A0 1E C3 90 4A 46 58 58 00

    编辑

    答案当然是使用BinaryWrite而不是Write。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Pavel Minaev    15 年前

    您不应该将二进制数据视为字符串。在本例中,ASCII编码仅支持0-127范围内的字符,因此不属于该范围的任何字节都将被视为无效,并替换为问号。使用 HttpResponse.BinaryWrite 相反:

    Response.BinaryWrite(st.FileContents);