将文件上传、下载(以二进制流保存到数据库)实现
将文件以二进制流格式存入数据库并获取文件路径,随后将其以二进制形式读取并存储于二进制数组中的操作详解
一、文件写入数据库
想要将文件以二进制流的形式存入数据库,首先需获取文件的路径并将其转化为二进制形式。这一过程通过编程实现,具体步骤如下:
1. 通过Http Context获取文件的实际路径。
2. 使用File.ReadAllBytes方法读取文件内容,将其转化为字节形式的二进制数组。
3. 与数据库建立连接,使用SQL语句将二进制数组赋值给相应的字段。
4. 执行更新操作,将文件二进制流写入数据库,并关闭数据库连接。
相关代码示例:
```csharp
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())
{
cmdmandText = "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;
}
```
二、从数据库读取文件
要从数据库中读取文件,只需按照路径在服务器上创建相应文件,然后将数据库中存储的二进制流写入新建文件即可。如果目标路径下已有同名文件,新文件会覆盖旧文件。
代码示例:
```csharp
//从数据库中读取文件流
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();
}
```
上述代码生动展示了将文件以二进制流形式存入数据库及从数据库中读取文件的操作流程,希望对你有所帮助。对于具体的操作环境和数据表结构,可能需要根据实际情况进行适当的调整。