FileUpload控件上传图片到数据库

 

ASP保存图片并显到网页实例 

2010-09-15 22:52:32|  分类: .NET |字号 订阅
using System.IO;
using System.Drawing;

保存图片:

前台:

将 form的enctype属性改为:

<form id="form1" runat="server" enctype="multipart/form-data">

 

后台:

protected void btnsaveiamge_Click(object sender, EventArgs e)

        {

            string getname = TextBox2.Text;

            if (fil1.HasFile)  //判断是否选种文件

            {

                string getfile = fil1.PostedFile.FileName;

                string imgtype = fil1.PostedFile.ContentType; //文件类型

                int i = getfile.LastIndexOf(".");

                string filename;

                filename = getfile.ToLower().Substring(i, getfile.Length - i);

                if (!(filename == ".jpg" || filename == ".jpeg" || filename == ".gif" || filename

== ".png"))

                {

                    ClientScript.RegisterStartupScript(ClientScript.GetType(), "uploaderr",

"<script language='javascript' defer>alert('上传文件格式不正确')</script>");

                    return;

                }

                //上传文件

                //FileUploadCompant(this.FileUpload1);  

                string strpath = fil1.PostedFile.FileName;  //文件名

                byte[] getimage = new byte[fil1.PostedFile.ContentLength];  //将图片转为二进制文件 

ContentLength表示上传文件的长度

                Stream filestream = fil1.PostedFile.InputStream;

                //读取数据

                filestream.Read(getimage, 0, fil1.PostedFile.ContentLength);

 

                strcon = "Data Source=(local); DataBase=NorthWind; UID=sa; PWD=200402025";

                testcon = new SqlConnection(strcon);

                testcon.Open();

                //用参数的方式保存二进制图片到数据库

                SqlCommand command = new SqlCommand("INSERT INTO ImageStore

(imgtitle,imgtype,imgdata,IMPATH)VALUES ( @imgtitle, @imgtype,@imgdata,@impath)", testcon);

                SqlParameter paretile = new SqlParameter("@imgtitle", SqlDbType.VarChar, 50);

                paretile.Value = getname;

                command.Parameters.Add(paretile);

                SqlParameter paretype = new SqlParameter("@imgtype", SqlDbType.VarChar, 50);

                paretype.Value = imgtype;

                command.Parameters.Add(paretype);

                SqlParameter pareimgdata = new SqlParameter("@imgdata", SqlDbType.Image);

                pareimgdata.Value = getimage;

                command.Parameters.Add(pareimgdata);

                SqlParameter pareimgpath = new SqlParameter("@impath", SqlDbType.VarChar, 200);

                pareimgpath.Value = strpath;

                command.Parameters.Add(pareimgpath);

                int iresult = command.ExecuteNonQuery();

                testcon.Close();

            }

        }

显示图片:

添加(*.ashx)文件

在文件下编辑

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

using System.IO;

using System.Drawing;

using System.Drawing.Imaging;

using System.Data;

using System.Data.SqlClient;

 

namespace MiSTest

{

    /// <summary>

    /// LoadImage 的摘要说明

    /// </summary>

    public class LoadImage : IHttpHandler

    {

        private SqlConnection testcon;

        private SqlCommand testcmd;

        string strsql;

        public void ProcessRequest(HttpContext context)

        {

            //context.Response.ContentType = "text/plain";

            //context.Response.Write("Hello World");

            try

            {

                string id = context.Request.QueryString["id"];

                if (!string.IsNullOrEmpty(id))

                {

                      string strcon="Data Source=(local); DataBase=NorthWind; UID=sa;

PWD=200402025";

                      testcon = new SqlConnection(strcon);

                      testcon.Open();

                      testcmd = new SqlCommand();

                      testcmd.Connection = testcon;

                      testcmd.CommandType = CommandType.Text;

                      strsql = "Select * from ImageStore where id="+ id + "";  //根据条件查出对应的

图片

                      testcmd.CommandText = strsql;

                      SqlDataReader sdr = testcmd.ExecuteReader();

                      if (sdr.Read())

                      {

                          context.Response.ContentType = sdr["IMGTYPE"].ToString();  //获取图片类型

                          context.Response.BinaryWrite((byte[])sdr["IMGDATA"]);     //显示图片必须

BinaryWrite这种写入的方式

                      }

                      testcon.Close();

                }

            }

            catch (Exception err)

            {

                context.Response.Write("<script language='javascript' defer='defer'> alert('" +

err.Message + "')</script>");

            }

        }

 

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

在页面中显示图片

protected void Button3_Click(object sender, EventArgs e)

        {

            Image1.ImageUrl = "LoadImage.ashx?id=" + txtimageid.Text.Trim() +""; //图片地址指向ashx

文件并向传递数片编号

        }

 

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值