简单的将图片上传到数据库

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
public partial class image : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected Int32 FileLength = 0;//记录文件长度变量
    protected void Button1_Click(object sender, EventArgs e)
    {
        HttpPostedFile UpFile = FileUpload1.PostedFile;//HttpPostedFile 对象用于读取图像
        FileLength = UpFile.ContentLength;//记录文件长度
        try
        {
            if (FileLength == 0)
            {
                Label1.Text = "<b>请选择要上传的图片</b>";
                return;
            }
            else
            {
                Byte[] Filebytearry = new Byte[FileLength];//图片临时存储
                Stream Streamobject = UpFile.InputStream;//建立数据流
                Streamobject.Read(Filebytearry, 0, FileLength);//读取图像文件数据,filebytearry为数据储存体,0为数据指针位置,filelength为数据长度
                string sqlstr = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
                using (SqlConnection Con = new SqlConnection(sqlstr))
                {
                    // SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString());
                     string sqlcmd = "INSERT INTO tImage(ImageDate,ImageContentType,ImageDescriiption,ImageSize) values(@Image,@ImageContentType,@ImageDescriiption,@ImageSize)";
                    SqlCommand cmd = new SqlCommand(sqlcmd, Con);
                    //cmd.Parameters.Add("@ImageStore", SqlDbType.Int).Value = Session["ImageStore"].ToString();
                    cmd.Parameters.Add("@Image", SqlDbType.Binary, FileLength).Value = Filebytearry;//记录图片信息
                    cmd.Parameters.Add("@ImageContentType", SqlDbType.VarChar, 50).Value = UpFile.ContentType;//记录图片类型
                    cmd.Parameters.Add("@ImageDescriiption", SqlDbType.VarChar, 200).Value = TextBox1.Text;//记录图片说明信息
                    cmd.Parameters.Add("@ImageSize", SqlDbType.BigInt, 8).Value = UpFile.ContentLength; ;//记录图片长度
                    Con.Open();
                    cmd.ExecuteNonQuery();
                    Con.Close();
                    Label1.Text = "<b>成功上传<b>";


                }
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message.ToString();
        }
    }

}

转载于:https://www.cnblogs.com/asher/archive/2012/05/13/2498000.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值