Home  >  Article  >  Backend Development  >  C# Upload and download files (save to database as binary stream)

C# Upload and download files (save to database as binary stream)

大家讲道理
大家讲道理Original
2016-11-10 14:54:102345browse

1. Write the file to the database in binary stream format

First obtain the file path, then read the file in binary and save it in a binary array, establish a connection with the database, and assign the binary array to the corresponding value in the SQL statement parameters to complete the operation of writing files to the database

/// 将文件流写入数据库  
/// </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. Read the file from the database and create a file in the corresponding format

To read the file from the database, just create the corresponding file according to the required path. Then just write the binary stream stored in the database into the newly created file

If there is a file with the same name in the directory, the original file will be overwritten

//从数据库中读取文件流  
//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();  
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn