1、將文件以二進(jìn)制流的格式寫入數(shù)據(jù)庫(kù)
首先獲得文件路徑,然后將文件以二進(jìn)制讀出保存在一個(gè)二進(jìn)制數(shù)組中,與數(shù)據(jù)庫(kù)建立連接,在SQL語(yǔ)句中將二進(jìn)制數(shù)組賦值給相應(yīng)的參數(shù),完成向數(shù)據(jù)庫(kù)中寫入文件的操作
復(fù)制代碼 代碼如下:
/// 將文件流寫入數(shù)據(jù)庫(kù)
/// /summary>
/// param name="filePath">存入數(shù)據(jù)庫(kù)文件的路徑/param>
/// param name="id">數(shù)據(jù)庫(kù)中插入文件的行標(biāo)示符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ù)庫(kù)中將文件讀出并建立相應(yīng)格式的文件
從數(shù)據(jù)庫(kù)中讀取文件,只需根據(jù)所需的路徑建立相應(yīng)的文件,然后將數(shù)據(jù)庫(kù)中存放的二進(jìn)制流寫入新建的文件就可以了
如果該目錄下有同名文件,則會(huì)將原文件覆蓋掉
復(fù)制代碼 代碼如下:
//從數(shù)據(jù)庫(kù)中讀取文件流
//shipmain.Rows[0]["ZBDocument"],文件的完整路徑
//shipmain.Rows[0]["ZBDocumentFile"],數(shù)據(jù)庫(kù)中存放的文件流
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ù)庫(kù)中的數(shù)據(jù)形成文件
fs.Write((byte[])shipmain.Rows[0]["ZBDocumentFile"], 0, arraySize);
fs.Close();
}
您可能感興趣的文章:- java實(shí)現(xiàn)FTP文件上傳與文件下載
- Flash兩個(gè)上傳示例ASP和PHP(原文件下載,包括后臺(tái)程序)
- JavaWeb實(shí)現(xiàn)文件上傳與下載實(shí)例詳解
- JAVA技術(shù)實(shí)現(xiàn)上傳下載文件到FTP服務(wù)器(完整)
- Java通過(guò)FTP服務(wù)器上傳下載文件的方法
- python實(shí)現(xiàn)的簡(jiǎn)單FTP上傳下載文件實(shí)例
- asp.net 多文件上傳,兼容IE6/7/8,提供完整代碼下載
- Jsp頁(yè)面實(shí)現(xiàn)文件上傳下載類代碼
- 最詳細(xì)的文件上傳下載實(shí)例詳解(推薦)