从SQL Server数据库检索文件

本文关键字:检索 文件 数据库 Server SQL | 更新日期: 2024-10-23 23:33:31

我正在构建一个网站,在那里我必须使用文件上传控制来附加支持日志/邮件等。我觉得将文件保存在数据库中是更好的选择。

我正在使用下面的代码上传文件。但是,我无法测试它,因为我不知道如何从数据库中检索文件。有人能帮我吗?

文件类型可以是任何类型。

代码:

FileUrl = "C:''Attachments''"+Path.GetFileName(UploadCtrl.NavigateUrl);
FileStream fs = new FileStream(FileUrl, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(FileUrl).Length;
buff = br.ReadBytes(Convert.ToInt32(numBytes));
SqlConnection conn = new SqlConnection(SQLSrc.ConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
string InsertQueryText = "insert into Attachments values ('" + Path.GetFileName(FileUrl) + "','" + MIME(Path.GetExtension(Att_Overview_Link.NavigateUrl)) + "','" + buff + "');";
command.CommandText = InsertQueryText;
command.ExecuteNonQuery();

这里,MIME是用户定义的函数,用于获取指定文件类型的MIME值。

前端:C#ASP.NET和SQL Server作为后端

从SQL Server数据库检索文件

首先修复代码以删除SQL注入漏洞:

FileUrl = "C:''Attachments''" + Path.GetFileName(UploadCtrl.NavigateUrl);
using (SqlConnection conn = new SqlConnection(SQLSrc.ConnectionString))
using (SqlCommand command = conn.CreateCommand())
{
   command.CommandText = "insert into Attachments values (@FileName, @MimeType, @FileBytes)";
   command.Parameters.AddWithValue("@FileName", Path.GetFileName(FileUrl));
   command.Parameters.AddWithValue("@MimeType", MIME(Path.GetExtension(Att_Overview_Link.NavigateUrl)));
   command.Parameters.AddWithValue("@FileBytes", File.ReadAllBytes(FileUrl));
   conn.Open();
   command.ExecuteNonQuery();
}

注意:我不确定您的UploadCtrl是什么,但大多数文件上载控件提供以Stream的形式直接访问上载的文件,而不是服务器上的文件名。根据此特定控件的工作方式,您可能需要更改读取上载文件的方式。

要检索文件,您需要选择相关的名称、MIME类型和字节,并将它们写入响应:

using (SqlConnection conn = new SqlConnection(SQLSrc.ConnectionString))
using (SqlCommand command = conn.CreateCommand())
{
   command.CommandText = "SELECT FileName, MimeType, FileBytes FROM Attachments WHERE PK = @PK";
   command.Parameters.AddWithValue("@PK", Request.QueryString["pk"]);
   conn.Open();
   using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))
   {
      if (reader.Read())
      {
         string name = reader.GetString(reader.GetOrdinal("FileName"));
         Response.AppendHeader("Content-Disposition", "attachment; filename=" + name);
         Response.ContentType = reader.GetString(reader.GetOrdinal("MimeType"));
         int startIndex = 0;
         byte[] buffer = new byte[4096];
         int fieldIndex = reader.GetOrdinal("FileBytes");
         int bytesRead = (int)reader.GetBytes(fieldIndex, startIndex, buffer, 0, buffer.Length);
         while (bytesRead != 0)
         {
            Response.OutputStream.Write(buffer, 0, bytesRead);
            Response.Flush();
            startIndex += bytesRead;
            bytesRead = (int)reader.GetBytes(fieldIndex, startIndex, buffer, 0, buffer.Length);
         }
      }
   }
}

如果使用的是SQL Server 2008或更高版本,则可以对varbinary(max)数据类型使用FILESTREAM存储。这篇MSDN文章包含了一些C#示例代码,这些代码应该可以完成您想要做的事情。它还展示了如何创建用于存储文件的表。