欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

将文件上传、下载(以二进制流保存到数据库)实现代码

程序员文章站 2024-03-02 23:08:34
1、将文件以二进制流的格式写入数据库 首先获得文件路径,然后将文件以二进制读出保存在一个二进制数组中,与数据库建立连接,在sql语句中将二进制数组赋值给相应的参数,完成向数...
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();
}
}
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();
}