將檔案上傳、下載(以二進位流儲存到資料庫)實現代碼

來源:互聯網
上載者:User

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();
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.