繁体   English   中英

使用ASP将ntext数据从SQL Server保存到文件目录

[英]Saving ntext data from SQL Server to file directory using asp

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

该脚本应该遍历各行,并将这些文件提取并保存到temp目录中。 给出了“文件名”和“内容类型”,而“数据”就是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,因此所有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标志至关重要,否则读取器将首先读取内存中的整个文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM