[英]Retrieve files from SQL Server database
我正在建立一個網站,我必須使用文件上傳控件來附加支持日志/郵件等...我覺得在數據庫中保存文件將是更好的選擇。
我使用下面的代碼上傳文件。 但是,我無法測試它,因為我不知道如何從數據庫中檢索文件。 有人可以幫我這個嗎?
文件類型可以是任何東西。
碼:
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 Injection漏洞 :
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或更新版本,則可以將FILESTREAM存儲用於varbinary(max)數據類型。 這篇MSDN文章包含一些C#示例代碼,可以完成您要完成的任務。 它還顯示了如何創建用於存儲文件的表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.