1、將檔案以二進位流的格式寫入資料庫
首先獲得檔案路徑,然後將檔案以二進位讀出儲存在一個位元組中,與資料庫建立串連,在SQL語句中將位元組賦值給相應的參數,完成向資料庫中寫入檔案的操作
複製代碼 代碼如下:/// 將檔案流寫入資料庫
/// </summary>
/// <param name="filePath">存入資料庫檔案的路徑</param>
/// <param name="id">資料庫中插入檔案的行標示符ID</param>
/// <returns></returns>
public int UploadFile(string filePath, string id)
{
byte[] buffer = null;
int result = 0;
if (!string.IsNullOrEmpty(filePath))
{
String file = HttpContext.Current.Server.MapPath(filePath);
buffer = File.ReadAllBytes(file);
using (SqlConnection conn = new SqlConnection(DBOperator.ConnString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "update DomesticCompanyManage_Main_T set ZBDocumentFile = @fileContents where MainID ='" + id + "'";;
cmd.Parameters.AddRange(new[]{
new SqlParameter("@fileContents",buffer)
});
conn.Open();
result = cmd.ExecuteNonQuery();
conn.Close();
}
}
return result;
}
else
return 0;
}
2、從資料庫中將檔案讀出並建立相應格式的檔案
從資料庫中讀取檔案,只需根據所需的路徑建立相應的檔案,然後將資料庫中存放的二進位流寫入建立的檔案就可以了
如果該目錄下有同名檔案,則會將原檔案覆蓋掉 複製代碼 代碼如下://從資料庫中讀取檔案流
//shipmain.Rows[0]["ZBDocument"],檔案的完整路徑
//shipmain.Rows[0]["ZBDocumentFile"],資料庫中存放的檔案流
if (shipmain.Rows[0]["ZBDocumentFile"] != DBNull.Value)
{
int arraySize = ((byte[])shipmain.Rows[0]["ZBDocumentFile"]).GetUpperBound(0);
FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(shipmain.Rows[0]["ZBDocument"].ToString()), FileMode.OpenOrCreate, FileAccess.Write);//由資料庫中的資料形成檔案
fs.Write((byte[])shipmain.Rows[0]["ZBDocumentFile"], 0, arraySize);
fs.Close();
}