Upload and download of files as binary streams to the database implementation code

  • 2020-06-07 04:22:28
  • OfStack

1. Write the file to the database as a binary stream
First, the file path is obtained, then the file is read out in base 2 and stored in a base 2 array, and the connection is established with the database. In THE SQL statement, the binary array is assigned to the corresponding parameter to complete the operation of writing the file to the database
 
///  Writes the file stream to the database  
/// </summary> 
/// <param name="filePath"> The path to the database file </param> 
/// <param name="id"> The line identifier for a file inserted in the database 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. Read the file from the database and create the file in the corresponding format
To read a file from the database, simply create the file based on the desired path, and then write the binary stream stored in the database to the newly created file
If there is a file with the same name in the directory, the original file is overwritten
 
// Reads a file stream from the database  
//shipmain.Rows[0]["ZBDocument"], The full path to the file  
//shipmain.Rows[0]["ZBDocumentFile"], The stream of files stored in the database  
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);// Form a file from the data in the database  
fs.Write((byte[])shipmain.Rows[0]["ZBDocumentFile"], 0, arraySize); 
fs.Close(); 
} 

Related articles: