public class myUpFile
{
//"server=.;uid=sa;pwd=;database=pubs";
private static string scn = ConfigurationSettings.AppSettings["strcn"].ToString();
private static SqlConnection cn = new SqlConnection(scn);
public myUpFile() {}
/// <summary>
/// 上传文件到数据库
/// 参数:
/// strCn 连接字符串 省略
/// strSql 数据查询 @Img,@sType,@Len
/// HPF HttpPostedFile 上传文件控件
/// 返回:文件名
/// </summary>
public static string UpFile(string strSql, HttpPostedFile HPF)
{
string fn = HPF.FileName.ToString(); // 取得文件名称
int fnLen = HPF.ContentLength; // 取得文件长度
//string fnType = HPF.ContentType.ToString(); // 取得文件类型
try
{
if (fnLen == 0) return ""; // 未选择上传的文件
Byte[] fnBuf = new Byte[fnLen]; // 创建存储图片文件的临时 Byte 数组
Stream stm = HPF.InputStream; // 建立数据流对象
stm.Read(fnBuf,0,fnLen); // 读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
SqlCommand cmd = new SqlCommand(strSql, cn); // 数据库操作
// 添加各项参数并赋值
cmd.Parameters.Add("@Img", SqlDbType.Image).Value = fnBuf; // 图片文件内容
cmd.Parameters.Add("@Len", SqlDbType.Int).Value = fnLen; // 文件长度
//cmd.Parameters.Add("@sType", SqlDbType.VarChar).Value = fnType; // 文件类型
if (cn.State != ConnectionState.Open )
cmd.Connection.Open(); // 打开连接
string rec = null;
cmd.ExecuteNonQuery(); // 执行数据库操作
if (rec!="1")
{
cmd.Connection.Close();
return "";
}
cmd.Connection.Close();
return fn;
}
catch (Exception ex) // 使用 Label 标签显示异常
{
ex.Message.ToString();
return "";
}
finally
{
}
}
/// <summary>
/// 从数据库中读取文件
/// 参数:
/// strCn 连接字符串 省略
/// strSql 数据查询 @Img,@sType,@Len
/// imgID 图片记录号 @Lsh
/// 返回: 文件名
/// </summary>
public static string DownFile(string strSql, int imgID)
{
string fn = @"c:/temp/Ademo.jpg";
SqlCommand cmd = new SqlCommand(strSql, cn);
if (imgID!=0) // 加参数值
cmd.Parameters.Add("@lsh", SqlDbType.Int).Value = imgID;
if (cn.State != ConnectionState.Open )
cmd.Connection.Open(); // 打开连接
SqlDataReader dr = cmd.ExecuteReader(); // 取数据
if(dr.Read()) // 有数据
{
FileStream fs = new FileStream(fn,FileMode.Create,FileAccess.ReadWrite); // 新建文件
BinaryWriter bw = new BinaryWriter(fs); // 建立二进制文件对象
bw.Write((byte[])dr["img"], 0, (int)dr["len"]); // 将字段值写入二进制文件中
bw.Close();
fs.Close();
dr.Close(); // 关闭
cmd.Connection.Close(); // 连续读取数据,最后关闭连接
return fn; // 返回文件名称
}
else
{
dr.Close(); // 关闭
cmd.Connection.Close(); // 连续读取数据,最后关闭连接
return ""; // 无文件返回
}
}
}