国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網(wǎng)站 > 幫助中心 > 正文

將文件上傳、下載(以二進制流保存到數(shù)據(jù)庫)實現(xiàn)代碼

2024-07-09 22:47:10
字體:
供稿:網(wǎng)友
1、將文件以二進制流的格式寫入數(shù)據(jù)庫
首先獲得文件路徑,然后將文件以二進制讀出保存在一個二進制數(shù)組中,與數(shù)據(jù)庫建立連接,在SQL語句中將二進制數(shù)組賦值給相應(yīng)的參數(shù),完成向數(shù)據(jù)庫中寫入文件的操作
代碼如下:
/// 將文件流寫入數(shù)據(jù)庫
/// </summary>
/// <param name="filePath">存入數(shù)據(jù)庫文件的路徑</param>
/// <param name="id">數(shù)據(jù)庫中插入文件的行標(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ù)庫中將文件讀出并建立相應(yīng)格式的文件
從數(shù)據(jù)庫中讀取文件,只需根據(jù)所需的路徑建立相應(yīng)的文件,然后將數(shù)據(jù)庫中存放的二進制流寫入新建的文件就可以了
如果該目錄下有同名文件,則會將原文件覆蓋掉
代碼如下:
//從數(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();
}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 宣武区| 蒙阴县| 太谷县| 修水县| 清新县| 体育| 南召县| 迁西县| 涿州市| 龙泉市| 靖远县| 道孚县| 阿合奇县| 湖州市| 彩票| 南投县| 铜梁县| 伊宁市| 北海市| 驻马店市| 永兴县| 秭归县| 铜陵市| 长丰县| 青神县| 五家渠市| 南木林县| 宜君县| 靖西县| 九龙坡区| 浮山县| 上饶县| 酉阳| 万宁市| 蒙山县| 简阳市| 木兰县| 阳原县| 柘城县| 蒲江县| 阜平县|