將文件上傳、下載(以二進制流保存到數據庫)實現代碼
2024-07-09 22:47:10
供稿:網友
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();
}