上传图片到数据库,下载图片到本地
/// <summary>
/// 上传图片到数据库
/// </summary>
/// <param name="UpFiles">html对象</param>
/// <param name="fieldname">字段名</param>
public void UploadfiletoDb(HtmlInputFile UpFiles1,HtmlInputFile UpFiles2,HtmlInputFile UpFiles3,string m_name)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CS"].ToString());
HttpPostedFile UpFile1 = UpFiles1.PostedFile;
HttpPostedFile UpFile2 = UpFiles2.PostedFile;
HttpPostedFile UpFile3 = UpFiles3.PostedFile;
FileLength1 = UpFile1.ContentLength; //记录文件长度
FileLength2 = UpFile2.ContentLength; //记录文件长度
FileLength3 = UpFile3.ContentLength; //记录文件长度
//try
//{
if ((FileLength1 == 0) || (FileLength2 == 0) || (FileLength3 == 0))
{ //文件长度为零时
Response.Write("<script>window.alert('请你选择你要上传的文件')</script>");
}
else
{
Byte[] FileByteArray1 = new Byte[FileLength1]; //图象文件临时储存Byte
Byte[] FileByteArray2 = new Byte[FileLength2]; //图象文件临时储存Byte
Byte[] FileByteArray3 = new Byte[FileLength3]; //图象文件临时储存Byte
Stream StreamObject1 = UpFile1.InputStream; //建立数据流对像
Stream StreamObject2 = UpFile2.InputStream; //建立数据流对像
Stream StreamObject3 = UpFile3.InputStream; //建立数据流对像
StreamObject1.Read(FileByteArray1, 0, FileLength1);
StreamObject2.Read(FileByteArray1, 0, FileLength2);
StreamObject3.Read(FileByteArray1, 0, FileLength3);
String SqlCmd = "update Member_tab set photofyj=@Image1,identitycardfyj=@Image2,presscardfyj=@Image3) where MemberName=@Mn";
SqlCommand CmdObj = new SqlCommand(SqlCmd, con);
CmdObj.Parameters.Add("@Image1", SqlDbType.Binary, FileLength1).Value = FileByteArray1;
CmdObj.Parameters.Add("@Image2", SqlDbType.Binary, FileLength2).Value = FileByteArray2;
CmdObj.Parameters.Add("@Image3", SqlDbType.Binary, FileLength3).Value = FileByteArray3;
CmdObj.Parameters.Add("@Mn", SqlDbType.NVarChar, 8).Value = m_name;
con.Open();
CmdObj.ExecuteNonQuery();
con.Close();
}
//}
//catch (Exception ex)
//{
// con.Close();
//}
}
//读取图片到页面
public void getimage(string mxingming,string str_fieldname)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CS"].ToString());
string p_sql = "SELECT " + str_fieldname + " FROM Member_tab WHERE MemberName = @MN";
SqlCommand CmdObj = new SqlCommand(p_sql, con);
CmdObj.Parameters.Add("@MN", SqlDbType.NVarChar).Value = mxingming;
con.Open();
SqlDataReader SqlReader = CmdObj.ExecuteReader();
if (SqlReader.Read())
{
if (SqlReader[str_fieldname]!= null)
{
try
{
byte[] photo = (byte[])SqlReader[str_fieldname];
Response.OutputStream.Write(photo, 0, photo.Length);
}
catch (Exception ex)
{
}
Response.End();
con.Close();
}
}
}