[英]Store/retrieve files to/from SQL Server database
我想允許用戶將文件附加到項目中。 文件可以是圖像,文檔,文本,zip文件等。
我在數據庫中創建了一個表,該表將存儲文件名,擴展名,大小,有關文件的注釋以及文件數據。 文件數據的列類型為VarBinary
(blob)。
現在,我已經從用戶那里獲取了輸入並將其存儲在本地列表視圖中(未綁定到db)。 我想在列表視圖行上進行迭代,並將它們存儲到數據庫中。 如何將文件數據存儲到BLOB列?
嘗試這個
// **** Read File/Image into Byte Array from Filesystem
public static byte[] GetPhoto(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return photo;
}
然后調用上面的函數添加到數據庫中
// **** Read Image from Filesystem and add it to the Database.
public void AddFileDataIntoDatabase(
string a,string b,string c, string photoFilePath)
{
// Read Image into Byte Array from Filesystem
byte[] photo = GetPhoto(photoFilePath);
// Construct INSERT Command
SqlCommand addEmp = new SqlCommand(
"INSERT INTO tablename ("+
"col1,col2,Col3,Photo) "+
"VALUES(@col1,@col2,@col3,@Photo)",_conn);
addEmp.Parameters.Add("@col1", SqlDbType.NVarChar, 20).Value = plastName;
addEmp.Parameters.Add("@col2", SqlDbType.NVarChar, 10).Value = pfirstName;
addEmp.Parameters.Add("@col3", SqlDbType.NVarChar, 30).Value = ptitle;
addEmp.Parameters.Add("@Photo", SqlDbType.Image, photo.Length).Value = photo;
// Open the Connection and INSERT the BLOB into the Database
_conn.Open();
addEmp.ExecuteNonQuery();
_conn.Close();
}
SELECT * FROM OPENROWSET(BULK N'<FILEPATH>', SINGLE_BLOB) AS Contents
It'll pull in the contents of the file as varbinary.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.