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 ='" + 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 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(); }