ASP.net(c#)将图片以二进制格式存储到数据库中

Posted on 2010-04-07 22:22  严武  阅读(355)  评论(0编辑  收藏  举报

using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
           
            string ImgPath = FileUpload1.PostedFile.FileName;
            string ImgName = ImgPath.Substring(ImgPath.LastIndexOf("//") + 1);
            string ImgExtend = ImgPath.Substring(ImgPath.LastIndexOf(".") + 1);
            if (!(ImgExtend == "bmp" || ImgExtend == "jpg" || ImgExtend == "gif"))
            {
                Label3.Text = "上传图片的格式不正确!";
                return;
            }
            int FileLen = this.FileUpload1.PostedFile.ContentLength;
            Byte[] FileData = new Byte[FileLen];
            HttpPostedFile hp = FileUpload1.PostedFile;//创建访问客户端上传文件的对象
            Stream sr = hp.InputStream;//创建数据流对象
            sr.Read(FileData, 0, FileLen);//将图片数据放到FileData数组对象实例中,其中0代表数组指针的起始位置,FileLen表示要读取流的长度(指针的结素位置)
            SqlConnection con = new SqlConnection("server=(local);user id=sa;pwd=;database=");
            con.Open();
            SqlCommand com = new SqlCommand("INSERT INTO tb_15 (name) VALUES (@imgdata)", con);
            com.Parameters.Add("@imgdata", SqlDbType.Image);
            com.Parameters["@imgdata"].Value = FileData;
            com.ExecuteNonQuery();
            Label1.Text = "保存成功!";
        }
        catch (Exception error)
        {

        
            Label1.Text = "处理出错!原因为:" + error.ToString();
        }
    }
   
}

Copyright © 2024 严武
Powered by .NET 8.0 on Kubernetes