【问题标题】:Saving ntext data from SQL Server to file directory using asp使用asp将ntext数据从SQL Server保存到文件目录
【发布时间】:2010-03-15 17:50:41
【问题描述】:

各种文件(pdf、图像等)存储在 MS SQL Server 上的 ntext 字段中。我不确定这个字段是什么类型,除了显示问号和未定义字符外,我假设它们是二进制类型。

脚本应该遍历行并将这些文件提取并保存到临时目录。给出了“文件名”和“内容类型”,“数据”是 ntext 字段中的任何内容。

我尝试了几种解决方案:

1) data.SaveToFile "/temp/"&filename, 2

错误:需要对象:'??????????????????????'

???

2) File.WriteAllBytes "/temp/"&filename, data

错误:需要对象:“文件”

我不知道如何导入这个,或者 MapPath 的服务器。 (提示:真是个菜鸟!)

3)
Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2

Dim BinaryStream
Set BinaryStream = CreateObject("ADODB.Stream")
BinaryStream.Type = adTypeBinary
BinaryStream.Open
BinaryStream.Write data
BinaryStream.SaveToFile "C:\temp\" & filename, adSaveCreateOverWrite

错误:参数类型错误、超出可接受范围或相互冲突。

4)
Response.ContentType = contenttype
Response.AddHeader "content-disposition","attachment;" & filename
Response.BinaryWrite data 
response.end

这可行,但文件应该保存到服务器而不是弹出另存为对话框。我不确定是否有办法将响应保存到文件。

感谢您阐明这些问题!

【问题讨论】:

  • NTEXT 仅适用于 TEXT - 但您似乎在其中有二进制文件.... 相当奇怪的设置!

标签: asp.net sql-server vb.net


【解决方案1】:

由于列是 NTEXT,所有 SqlClient 对象都会将其解释为 unicode 字符串,这将导致各种问题。您应该将列更改为 varbinary(max)。

一旦您将列作为真正的二进制文件,适用于文件,您就可以从 SqlClient 读取列流并将流写入响应(跳过中间临时文件):

void StreamFileToResponse(int id, SqlConnection connection) {
SqlCommand cmd  = new SqlCommand(@"select data from table where id = @id", connection);
cmd.Paramaters.AddWithValue("@id", id);
using(SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess) {
   while (rdr.Read()) {
      Stream data = rdr.GetSqlBytes(0).Stream;
      byte[] buffer = new byte[4096];
      while(int read = data.Read(buffer, 0, 4096)) {
         Response.BinaryWrite(buffer, 0, read);
      }
   }
}

传递给 ExecuteReader 的 SequentialAcccess 标志很关键,否则读取器将首先读取内存中的整个文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多