C#將檔案上傳、下載(以二進位串流儲存到資料庫)

大家讲道理
發布: 2016-11-10 14:54:10
原創
2345 人瀏覽過

1、將檔案以二進位流的格式寫入資料庫

首先獲得檔案路徑,然後將檔案以二進位串流的格式寫入資料庫

先取得檔案路徑,然後將檔案以二進位陣列賦值給對應的參數,完成向資料庫中寫入文件的操作

/// 将文件流写入数据库  
/// </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 =&#39;" + id + "&#39;";;  
                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();  
}
登入後複製
🎜🎜
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!