1、將文件以二進制流的格式寫入數(shù)據(jù)庫
首先獲得文件路徑,然后將文件以二進制讀出保存在一個二進制數(shù)組中,與數(shù)據(jù)庫建立連接,在SQL語句中將二進制數(shù)組賦值給相應的參數(shù),完成向數(shù)據(jù)庫中寫入文件的操作
復制代碼 代碼如下:
/// 將文件流寫入數(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ù)庫中將文件讀出并建立相應格式的文件
從數(shù)據(jù)庫中讀取文件,只需根據(jù)所需的路徑建立相應的文件,然后將數(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();
}
您可能感興趣的文章:- java實現(xiàn)FTP文件上傳與文件下載
- Flash兩個上傳示例ASP和PHP(原文件下載,包括后臺程序)
- JavaWeb實現(xiàn)文件上傳與下載實例詳解
- JAVA技術(shù)實現(xiàn)上傳下載文件到FTP服務器(完整)
- Java通過FTP服務器上傳下載文件的方法
- python實現(xiàn)的簡單FTP上傳下載文件實例
- asp.net 多文件上傳,兼容IE6/7/8,提供完整代碼下載
- Jsp頁面實現(xiàn)文件上傳下載類代碼
- 最詳細的文件上傳下載實例詳解(推薦)