我尝试从SQL Server检索varbinary值数组,而不是尝试将它们存储在一个文本文件中,用户可以下载该文件,但不确定如何将该文件返回到Response.Redirect()或如何返回该文本文件。
public byte[] GenerateTextFile()
{
if (m_Template == CFCTemplate.GETTXTDATA)
{
SqlCommand cmd = new SqlCommand("SELECT SpecData FROM Spec WHERE TestID=" + SpecTestID);
InternalSalesDB.Instance.query(cmd);
DataTable dt = InternalSalesDB.Instance.query(cmd).Tables[0];
if (dt.Rows.Count > 0)
{
byte[] binarySpec = (byte[])dt.Rows[0][0];
FileStream fileStream = new FileStream("TestData.txt",FileMode.Append);
fileStream.Write(binarySpec, 0, binarySpec.Length);
fileStream.Flush();
fileStream.Close();
}
}
//need return statement here ??
}发布于 2014-04-05 02:49:55
为什么不让用户直接以文本文件的形式下载varbinary呢?
使用通用处理程序(.ashx)很容易完成,当您从项目>添加>新建项添加通用处理程序时,模板提供了大部分代码...>通用处理程序
Public Class DocHandler
Implements IHttpHandler, IRequiresSessionState声明一个字节数组
Dim buffer() As Bytecontext参数允许您在需要时访问会话数据。在本例中,我访问了文件名,但这可以很容易地从DB调用或处理程序的url参数中获取。
Sub ProcessRequest(ByVal context As HttpContext) _
Implements IHttpHandler.ProcessRequest
If context.Response.IsClientConnected Then
If context.Request.UrlReferrer IsNot Nothing Then
If context.Session("case_document_key") IsNot Nothing Then在这里初始化DB调用,我假定有一个名为Cmd的SqlCommand变量
Dim yourvarbinaryfield = Cmd.ExecuteScalar()将返回的varbinary字段转换为字节数组buffer =DirectCast(您的yourvarbinaryfield,Byte())
这就是魔术。
将处理程序响应头内容部署设置为以文本形式下载文件:
context.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", context.Session("YourFileName")))
context.Response.ContentType = "text/plain"
context.Response.BinaryWrite(buffer)
context.Response.OutputStream.Write(buffer, 0, buffer.Length)
context.Response.Flush()
End If
End If
End If
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property结束类
https://stackoverflow.com/questions/22870111
复制相似问题