教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 asp.net 文件上传、下载(二进制流保存到数据库)的代码

asp.net 文件上传、下载(二进制流保存到数据库)的代码

发布时间:2016-04-15   编辑:jiaochengji.com
本文介绍下,asp.net程序将文件以二进制流的格式写入数据库的方法,在文件的上传与下载中,应用还是比较广泛的。有需要的朋友,参考下吧。

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();
}
} //by www.jbxue.com
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();
}

您可能感兴趣的文章:
asp.net 文件上传、下载(二进制流保存到数据库)的代码
asp.net上传文件的方法浅析
asp.net 上传下载(二进制流)的代码
.net二进制形式存储文件与图片的实例代码
asp.net性能优化方法-数据库访问性能优化
asp.ent 图片上传数据库的代码(c#)
php图片上传并保存到MySql数据库的实现代码
在ASP.NET中跟踪和恢复大文件下载
HTML5中indexedDB 数据库的相关介绍
indexedDB 数据库

[关闭]
~ ~