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();
}
您可能感興趣的文章:- java實現FTP文件上傳與文件下載
- Flash兩個上傳示例ASP和PHP(原文件下載,包括后臺程序)
- JavaWeb實現文件上傳與下載實例詳解
- JAVA技術實現上傳下載文件到FTP服務器(完整)
- Java通過FTP服務器上傳下載文件的方法
- python實現的簡單FTP上傳下載文件實例
- asp.net 多文件上傳,兼容IE6/7/8,提供完整代碼下載
- Jsp頁面實現文件上傳下載類代碼
- 最詳細的文件上傳下載實例詳解(推薦)