Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Here is my code, plz see where is error:
C#
protected void btnSubmit_Click(object sender, EventArgs e)
 {
     SqlConnection connection = null;
     try
     {
         FileUpload img = (FileUpload)imgUpload;
         Byte[] imgByte = null;
         if (img.HasFile && img.PostedFile != null)
         {
             //To create a PostedFile
             HttpPostedFile File = imgUpload.PostedFile;
             //string Filename = Path.GetFileName(imgUpload.PostedFile.FileName);
             //imgUpload.SaveAs(Server.MapPath("~/images/"+Filename));
             //Create byte Array with file len
             imgByte = new Byte[File.ContentLength];
             //force the control to load data in array
             File.InputStream.Read(imgByte, 0, File.ContentLength);
         }
         // Insert the picture tag and image into db
         string conn = ConfigurationManager.ConnectionStrings["ProductConnectionString1"].ConnectionString;
         connection = new SqlConnection(conn);
         connection.Open();
         string sql = "INSERT INTO Album(Picture_Tag,Pic) VALUES(@tag,@pic) SELECT @@IDENTITY";
         SqlCommand cmd = new SqlCommand(sql, connection);
         cmd.Parameters.AddWithValue("@tag", txtTags.Text);
         cmd.Parameters.AddWithValue("@pic", imgByte);
         int id = Convert.ToInt32(cmd.ExecuteScalar());
         lblResult.Text = String.Format("Picture ID is {0}", id);
         ListView1.DataBind();
     }
     catch
     {
         lblResult.Text = "There was an error";
     }
     finally
     {
         connection.Close();
     }
 }


This is .aspx page:
XML
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
 <div>
        Image
        <asp:Label ID="lblTags" runat="server" Text="Tags"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txtTags" runat="server" Width="453px"></asp:TextBox>
        <br />
        <asp:Label ID="lblImage" runat="server" Text="Upload Picture"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:FileUpload ID="imgUpload" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
            Text="Submit" />
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp<asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
    <br />
    <hr />
    </div>

<asp:ListView ID="ListView1" GroupItemCount="4" runat="server" DataKeyNames="PICID" DataSourceID="SqlDataSource1">
        <LayoutTemplate>
            <asp:Placeholder
            id="groupPlaceholder"
            runat="server" />
        </LayoutTemplate>
        <GroupTemplate>
            <div>
            <asp:Placeholder
            id="itemPlaceholder"
            runat="server" />
            </div>
        </GroupTemplate>
        <ItemTemplate>

            <asp:Image id="picAlbum" runat="server" AlternateText='<% #Eval("Picture_Tag") %>' ImageUrl='<% #"ShowImage.ashx?id=" + Eval("PICID") %>' />
        </ItemTemplate>
        <EmptyItemTemplate>

        </EmptyItemTemplate>
    </asp:ListView>
      <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:ProductConnectionString1 %>"
        ProviderName="System.Data.SqlClient"
        SelectCommand="SELECT [PICID],Picture_Tag, [Pic] FROM [Album]"></asp:SqlDataSource>
</asp:Content>



and this is my handler class:

C#
<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        Int32 picid;
        if (context.Request.QueryString["id"] != null)
            picid = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        Stream strm = ShowAlbumImage(picid);
        byte[] buffer = new byte[4096];
        int byteSeq = strm.Read(buffer, 0, 4096);

        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 4096);
        }
        //context.Response.BinaryWrite(buffer);
    }

    public Stream ShowAlbumImage(int picid)
    {
        string conn = ConfigurationManager.ConnectionStrings["ProductConnectionString1"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT Pic FROM Album WHERE PICID = @ID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", picid);
        connection.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])img);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

here i am getting Alt text fine but when i call handler class through Asp:Image tag then there is no result. And no image is showing on page.
Posted
Updated 11-Jun-12 0:17am
v2
Comments
bbirajdar 11-Jun-12 6:19am    
Have you registered the handler in web.config?

you can use this library:
http://aspnet.codeplex.com/releases/view/16449[^]

You can find an example for Database Images too
 
Share this answer
 
my code like this

aspx page

<asp:image height="150px" width="150px" style="width:150px; height:150px;" id="Image1" runat="server" xmlns:asp="#unknown">

aspx.cs page

Image1.ImageUrl = "~/StudentManage/AjaxPhoto.ashx?studentid=" + StudentId;
Image1.Height = 300;
Image1.Width = 300;

handler class
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpg";
context.Response.Buffer = true;
int id;

try
{
if (int.TryParse(context.Request.QueryString["Id"], out id))
{
IDataReader reader = StudentBLL.GetPhotoById(id);

byte[] bytes = new byte[1024];
int currentOffset = 0;

if (reader.Read())
{
while (reader.GetBytes(0, currentOffset, bytes, 0, bytes.Length) > 0)
{
currentOffset += bytes.Length;
context.Response.BinaryWrite(bytes);
}
}

context.Response.Flush();
}
else
{
throw new ArgumentException("未知参数程序未能解析");
}
}
catch (Exception)
{

//throw;
}
}

GetPhotoById method
public IDataReader GetPhotoById(int id)
{
try
{
string sqlSelect = "select photo from tb_recruit_Student where Id=@Id";
DbCommand cmd = db.GetSqlStringCommand(sqlSelect);
db.AddInParameter(cmd, "Id", DbType.Int32, id);
IDataReader reader = db.ExecuteReader(cmd);
return reader;
}
catch (Exception)
{
throw;
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900