存储图片到数据库

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

public partial class Img : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            //上传的图片文件到Image
            System.Drawing.Image img = System.Drawing.Image.FromFile(FileUpload1.PostedFile.FileName);

            //以JPEG格式保存到内存中
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            using (SqlConnection con = new SqlConnection (""))
            {
                SqlCommand cmd = new SqlCommand("spInsertImage", con);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add("@ImageBinary", System.Data.SqlDbType.Image);

                //图片以二进制数据方式
                cmd.Parameters["@ImageBinary"].Value = ms.ToArray();
                con.Open();
                try
                {
                    //调用存储过程
                    cmd.ExecuteNonQuery();
                    Response.Write("Done");
                }
                catch (System.Exception ex)
                {
                    con.Close();
                    Response.Write("Error");
                }
            }

            img.Dispose();
            ms.Dispose();
            ms.Flush();
        }
        catch (System.Exception ex)
        {
        }

    }
}

你可能感兴趣的:(数据库)