将图片保存到数据库并用GridView显示

来源:互联网 发布:淘宝如何延长付款 编辑:程序博客网 时间:2024/05/20 06:27

            int len = Upload.PostedFile.ContentLength;
            byte[] pic = new byte[len];
            Upload.PostedFile.InputStream.Read(pic, 0, len);// 插入图片和说明到数据库中

 

ashx读取上传至数据库中的图片

public class GetImage : IHttpHandler {
     public bool IsReusable{
        get {
            return true;
        }
    }

    public void ProcessRequest(HttpContext context){
        // Set up the response settings
        context.Response.ContentType = "image/jpg";
        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.BufferOutput = false;

        string  photoId ="";
        Stream stream = null;

        if (context.Request.QueryString["kp_item_no"] != null &&
            context.Request.QueryString["kp_item_no"] != "") {
            photoId = context.Request.QueryString["kp_item_no"].ToString ();
            stream = GetPhoto(photoId);
        }

        const int buffersize = 1024 * 16;
        byte[] buffer = new byte[buffersize];
        int count = stream.Read(buffer, 0, buffersize);
        while (count > 0) {
            context.Response.OutputStream.Write(buffer, 0, count);
            count = stream.Read(buffer, 0, buffersize);
        }
       
        context.Response.End();
    }
   

    public Stream GetPhoto(string photoId)
    {
        SqlConnection myConnection = new SqlConnection(
            ConfigurationManager.ConnectionStrings["mydbConnectionString"].ConnectionString);
        SqlCommand myCommand = new SqlCommand
            ("SELECT cast(isnull([goods_picture],'0')as image ) FROM [jb_spzl_image] WHERE [kp_item_no]=@PhotoID ",
            myConnection);
        myConnection.Open();
        myCommand.CommandType = System.Data.CommandType.Text;
        // myCommand.Parameters.Add(new SqlParameter("@PhotoID", photoId));
        myCommand.Parameters.AddWithValue("@PhotoID", photoId);
 
       
        object result = myCommand.ExecuteScalar();

        try
        {
            return new MemoryStream((byte[])result);
        }
        catch (ArgumentNullException e)
        {
            return null;
        }
        finally
        {
            myConnection.Close();
        }

    }
}
 

原创粉丝点击