我的任务是上传图像并将 Gridview 绑定到显示图像。
我正在使用通用处理程序,并抛出以下错误:“类型 HttpHandler 不继承表单'System.web.IHttpHandler'”。
任何人都可以帮忙。
我的代码:HttpHandler.ashx
<%@ WebHandler Language="C#" Class="HTTPHandler" %>
using System;
using System.Web;
using System.Web.Configuration;
using System.Configuration;
using System.Data.SqlClient;
public class HTTPHandler { //IHttpHandler {
string strcon = ConfigurationManager.AppSettings["ImagConnectionString2"].ToString();
public void ProcessRequest (HttpContext context) {
string imageid = context.Request.QueryString["ImageId"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Image from image where ImageId=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
}
我的代码:Button_Click
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Configuration;
using System.Data;
using System.Data.SqlTypes;
public partial class _Default : Page
{
string strcon = ConfigurationManager.ConnectionStrings["ImagConnectionString2"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (fileuploadImage.HasFile)
{
int length = fileuploadImage.PostedFile.ContentLength;
//create a byte array to store the binary image data
byte[] imgbyte = new byte[length];
//store the currently selected file in memeory
HttpPostedFile img = fileuploadImage.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string imagename = txtImageName.Text;
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO image (ImageName,Image) VALUES (@imagename,@imagedata)", connection);
cmd.Parameters.Add("@imagename", SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();
txtImageName.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [image]", connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}
}