溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何將文件以二進制流保存到數(shù)據(jù)庫

發(fā)布時間:2021-10-14 10:04:45 來源:億速云 閱讀:264 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)如何將文件以二進制流保存到數(shù)據(jù)庫的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

1、將文件以二進制流的格式寫入數(shù)據(jù)庫
首先獲得文件路徑,然后將文件以二進制讀出保存在一個二進制數(shù)組中,與數(shù)據(jù)庫建立連接,在SQL語句中將二進制數(shù)組賦值給相應(yīng)的參數(shù),完成向數(shù)據(jù)庫中寫入文件的操作

復(fù)制代碼 代碼如下:


/// 將文件流寫入數(shù)據(jù)庫
/// </summary>
/// <param name="filePath">存入數(shù)據(jù)庫文件的路徑</param>
/// <param name="id">數(shù)據(jù)庫中插入文件的行標示符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、從數(shù)據(jù)庫中將文件讀出并建立相應(yīng)格式的文件
從數(shù)據(jù)庫中讀取文件,只需根據(jù)所需的路徑建立相應(yīng)的文件,然后將數(shù)據(jù)庫中存放的二進制流寫入新建的文件就可以了
如果該目錄下有同名文件,則會將原文件覆蓋掉

復(fù)制代碼 代碼如下:


//從數(shù)據(jù)庫中讀取文件流
//shipmain.Rows[0]["ZBDocument"],文件的完整路徑
//shipmain.Rows[0]["ZBDocumentFile"],數(shù)據(jù)庫中存放的文件流
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);//由數(shù)據(jù)庫中的數(shù)據(jù)形成文件
fs.Write((byte[])shipmain.Rows[0]["ZBDocumentFile"], 0, arraySize);
fs.Close();
}

感謝各位的閱讀!關(guān)于“如何將文件以二進制流保存到數(shù)據(jù)庫”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI