插入二进制图片

来源:互联网 发布:奉化淘宝司法拍卖网 编辑:程序博客网 时间:2024/05/01 03:41

protected void Button1_Click(object sender, EventArgs e)
    {
       
if (FileUpload1.HasFile == false)
        {
            Label1.Text
= "上载的文件不存在";
           
return;
        }
        HttpPostedFile file
= FileUpload1.PostedFile;
       
if (file.ContentLength <= 0)
        {
            Label1.Text
= "上载的文件的内容为空,不能上载";
           
return;
        }

       
///获取文件的名称和扩展名
        string vfilename = System.IO.Path.GetFileName(file.FileName);

       
///定义保存文件的二进制数据
        byte[] data = new byte[file.ContentLength];
       
///读取文件的二进制数据
        file.InputStream.Read(data, 0, file.ContentLength);

       
///获取配置文件Web.config中的连接字符串
        string conString = ConfigurationManager.ConnectionStrings["WEB2ASPNET2DBConnectionString"].ConnectionString;
       
///创建连接SQL Server数据库的SqlConnection对象
        SqlConnection myCon = new SqlConnection(conString);
       
string cmdText = "INSERT INTO [Files] ([Name],[Type],[Data])VALUES('"
           
+ vfilename + "','"
           
+ file.ContentType + "',@Data)";
        SqlCommand myCmd
= new SqlCommand(cmdText, myCon);

       
///添加SQL语句的参数
        SqlParameter pData = new SqlParameter();
        pData.ParameterName
= "@Data";
        pData.Value
= data;
        pData.Direction
= System.Data.ParameterDirection.Input;
        myCmd.Parameters.Add(pData);

       
try
        {
            myCon.Open();           
///打开连接           
            myCmd.ExecuteNonQuery();///将数据库保存到数据库
            Label1.Text = "上载文件:“" + vfilename + "” 成功。";
        }
       
catch (SqlException sqlex)
        {  
///如果连接失败,则显示错误信息
            Label1.Text = sqlex.Message;
        }
       
finally
        {  
///关闭已经打开的连接
            if (myCon != null)
            {
                myCon.Close();
            }
        }
    }

原创粉丝点击