利用FileUpload读写BLOB(转载)

来源:互联网 发布:淘宝卖家商品详情编辑 编辑:程序博客网 时间:2024/06/05 19:51

数据库中必需存储的几个字段picture(用来存储图片image类型),psize(存储图片大小int)

我用的数据库里还有一个pname(用来存储图片名称nvarchar(50)

 

首先:在引用中添加

using System.Data.SqlClient;//数据库连接时调用
using System.IO;//
写入数据库时用得着

确定按钮事件

 

protected void Button1_Click(object sender, EventArgs e)
    {
        #region   //
图片存储
        if (FileUpload1.PostedFile.FileName == "")
        {
            Label1.Text = "
您还没有选择图片!";
            return;
        }
        else
        {

            HttpPostedFile hp=FileUpload1.PostedFile;//创建访问客户端上传文件的对象
            string filepath = FileUpload1.PostedFile.FileName;//
取得路径

            int uplength = FileUpload1.PostedFile.ContentLength;//图片大小
            string filename = filepath.Substring(filepath.LastIndexOf("//") + 1);//
文件名称带后缀名
            string name = filename.Substring(0, filename.Length - 4);//
文件名不带后缀名
            string fileEx = filepath.Substring(filepath.LastIndexOf(".") + 1);//
后缀名
            //
判断图片格式
            if (fileEx == "jpg" || fileEx == "bmp" || fileEx == "gif")
            {
                FileUpload1.PostedFile.SaveAs("D:/picture/" + filename);//
先将文件上传到服务器,保存后再删除,文件夹必需有写入权限
                string path = "D:/picture/" + filename;//
文件在服务器上的地址

                Stream sr = hp.InputStream;//创建数据流对象
                byte[] b = new byte[uplength];//
定义byte型数组
                sr.Read(b, 0, uplength);//
将图片数据放到b数组对象实例中,其中0代表数组指针的起始位置,uplength表示要读取流的长度(指针的结束位置)

                try
                {
                    con.Open();
                    string sql = "insert into picture(picture,pname,ptype,psize) values(@picture,@pname,@ptype,@psize)";
                    SqlCommand cmd = new SqlCommand(sql, con);

                    //必需这么写不可以写成
                    //string sql = "insert into picture(picture,pname,ptype,psize) values('"+b+"','"+name+"','"+filetype+"','"+uplength+"'")";
                    //
要不显示不出来
                    cmd.Parameters.Add("@picture", b);
                    cmd.Parameters.Add("@pname", name);
                    cmd.Parameters.Add("@ptype", filetype);
                    cmd.Parameters.Add("@psize", uplength);
                    cmd.ExecuteNonQuery();
                    Label2.Text = "
上传成功";
                    con.Close();
                }
                catch (Exception ex)
                {
                    Label1.Text = ex.Message.ToString();
                    Label2.Text = "
添加失败";
                }
                File.Delete(path);//
将上传的图片删除
            }
            else
            {
                Label1.Text = "
上传图片扩展名错误";
            }
        }
        #endregion
        }

 

 

显示时根据名称找到ID进行显示, imageurl 转向别一个页面

protected void Button2_Click(object sender, EventArgs e)
    {
        con.Open();//
打开连接
        string sql = "select id,picture,ptype from picture where pname='" + TextBox1.Text.Trim() + "'";
        SqlDataAdapter sda = new SqlDataAdapter(sql,con);
        DataSet ds = new DataSet();
        sda.Fill(ds);        int ID = Convert.ToInt32(ds.Tables[0].Rows[0]["id"]);
        Image1.ImageUrl="img.aspx?id="+ID+"";//
转向另一页面
        con.Close();//
关闭连接
    }

 

img.aspx页面直接在后台写代码

protected void Page_Load(object sender, EventArgs e)
    {
        int id;
        int.TryParse(this.Request.QueryString["id"], out id);//
获取传过来图片ID参数
        if (id != 0)
        {
            //int imgID = Convert.ToInt32(Request.QueryString["id"]);
            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["sqlcon"]);//
加接数据库
            con.Open();//
打开连接
            string sql = "select * from picture where id='" + id + "'";
            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataReader dr = cmd.ExecuteReader();
            try
            {
                dr.Read();
                Response.Clear();  
                Response.ContentType = (string)dr["ptype"];
                Byte[] b = (byte[])dr["picture"];

                Response.OutputStream.Write(b 0, (int)dr["psize"]);
                Response.End();
                con.Close();//
关闭连接
            }
            catch (Exception ex)
            {
                Response.Write(ex);//
显示错误信息
            }
        }
    }

原创粉丝点击