C#將文件上傳、下載(以二進制流保存到數據庫)

jopen 9年前發布 | 5K 次閱讀 C#

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

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!