Click here to Skip to main content
16,016,301 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Its really different problem.please someone help me. in retrieving image stored in sql databaseto to a page or to image control. i tried everything since last four days.. pls help.
HI iam yogesh, i am not new to asp.net or c#. i have succesfully stored images in sql table(datatype-> image), using the following code

C#
HttpPostedFile file = myfile.PostedFile;
               int size = file.ContentLength;
               string strtype = file.ContentType;
               string fn = file.FileName;
               byte[] bit = new byte[size];
               file.InputStream.Read(bit, 0, bit.Length);
               SqlCommand savecmd = new SqlCommand("insert into reginfo (userid,password,name,surname,sex,country,imgdata,imgsize,imgstrtype,imgfilename) values (" + "'" + txtregid.Text + "'," + "'" + txtregpassword.Text + "'," + "'" + txtname.Text + "'," + "'" + txtsurname.Text + "'," + "'" + ddsex.Text + "'," + "'" + ddcountry.Text + "'"+","+"'"+bit+"'"+","+size+","+"'"+strtype+"'"+","+"'"+fn+"'"+")", methods.connection);
               savecmd.ExecuteNonQuery();


I USED THE FOLLOWING IN MYPAGE.ASPX----
ASP.NET
<form id="form1" method="post"  runat="server" enctype="multipart/form-data">


now when iam trying to fetch the image from table on html image control it shows the image control without image. it also shows a small image icon on upper left corner.
i have also used image.ashx (handler) but still failed. my code with handler and without handler are:
WITH HANDLER--------
C#
using System;
using System.Data;
using System.Web;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
using salefunctions;
namespace ADVANCED_FORUM
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class iamge : IHttpHandler
    {
        public string quid;
        public void ProcessRequest(HttpContext context)
        {
           if (context.Request.QueryString["user"]!=null)
           {
                quid = context.Request.QueryString["user"];
               context.Response.ContentType="image/jpeg";
               Stream strm = showimage(quid);
               byte[] buffer = new byte[4096];  
               int buffseq = strm.Read(buffer,0, 4096);
               while(buffseq>0)
               {
                   context.Response.OutputStream.Write(buffer, 0, buffseq);
                   buffseq = strm.Read(buffer,0, 4096);
               }
            }
            //filemethod();
        }
        public Stream showimage(string id)
        {
            methods.createcon("forum"); /* this is method to create connection and forum is database name */
            SqlCommand dispimgcmd = new SqlCommand("select imgdata from reginfo where userid=@aid", methods.connection);
            dispimgcmd.Parameters.AddWithValue("@aid", id);
            object mimg = dispimgcmd.ExecuteScalar();
            return new MemoryStream((byte[])mimg);
   
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
       
    }
}

CODE WITHOUT HANDLER (TO DISPLAY IMAGE ON PAGE);
C#
using System;
using System.Data;
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.IO;
using System.Data.SqlClient;
using salefunctions;
namespace ADVANCED_FORUM
{
    public partial class imageview : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //filemethod();
            methods.createcon("forum"); /* this is method to create connection and forum is database name */
            SqlCommand dispimgcmd=new SqlCommand("select * from reginfo where userid=" + "'" + Session["mlinkquid"] + "'", methods.connection);
            SqlDataReader drdispimg = dispimgcmd.ExecuteReader();
            drdispimg.Read();
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = (string)drdispimg["imgstrtype"];
            Response.OutputStream.Write((byte[])drdispimg["imgdata"],0,(int)drdispimg["imgsize"]);
            methods.connection.Close();
            Response.End();
            //string user = "";
            //image1.Src = "iamge.ashx?user=" + Session["mlinkquid"];
          }
      
    }
}

plsssssssssssss someone help me... i have checked everything,contenttype,contentlength.all is ok but iam not getting the image.
i think there is some problem with iamges. because even when i dragged an img control and set "src" property as
HTML
src="d:\images\srk.jpg"
or
HTML
src="~/images/srk.jpg"
it shows the image atdesign time but it dosent shows the same (at runtime) i:e when i run the project, the same problem happens, img control displays with no image.
plsssssssssssssss iam tired of asking for solution. pls help me. its very imp for me... IF THERE ARE ANY MASTERS IN ASP,C#


[edit]SHOUTING removed, Subject - OriginalGriff[/edit]
Posted
Updated 8-Aug-11 8:16am
v2
Comments
OriginalGriff 8-Aug-11 14:16pm    
DON'T SHOUT. Using all capitals is considered shouting on the internet, and rude (using all lower case is considered childish). Use proper capitalisation if you want to be taken seriously.

Take a look at this Code Project Q/A To display binary formatted image from database[^]
 
Share this answer
 
I would not have used concatenated strngs either.
I guess t actually wont work to insert byte data that way.
First insert using the command objec with parameters. Sugest u use the image data type for the binary part of the image.

Then retreve the image. If u are using an aspx-Page as the image, dont forget to set the correct mime-type of the page.

Also dont forget that the page u are using as image must not include ANY thing else than the image. So remove anything from the page that is getin rendered.
Hoever the image-control is sugested to get used for this.
 
Share this answer
 
Comments
yogesh a sharma 9-Aug-11 1:02am    
thankssssssssssssss, mattias very much sir your suggestion did my job.. it was the problem of storing in wrong forma.. because of not using parameters in sql query's.. thanks very much..............
The way I do it is with a handler:
You need to embed an image into your webpage:
<img alt="" src="ImageFromDb.ashx" />

You then need to code to access and display the image.
In VS, right click your project, and select "Add new Item"
When the dialog appears, select "Generic Handler" from the list, and call it "ImageFromDb"
Press [ENTER].
The code below will display an image dynamically:
<%@ WebHandler Language="C#" Class="ImageFromDb" %>

C#
using System;
using System.Web;
using System.Data.SqlClient;
public class ImageFromDb : IHttpHandler
    {
    public bool IsReusable
        {
        get { return false; }
        }
    public void ProcessRequest(HttpContext context)
        {
        using (SqlConnection con = new SqlConnection(@"Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=myDatabase;Integrated Security=True"))
            {
            con.Open();
            SqlCommand com = new SqlCommand("SELECT * FROM myTable WHERE id=1", con);
            SqlDataReader read = com.ExecuteReader();
            if (read.Read())
                {
                object o = read["Image"];
                if (!(o is DBNull))
                    {
                    // Image found.
                    context.Response.ContentType = "image/JPEG";
                    context.Response.BinaryWrite((byte[]) o);
                    }
                }
            }
        }
    }
You will have to modify this code to suit your database and user id system, but that is the complete code I use.



"thanks for reply but it also does't work. the same problem exists."


Then the problem is in the image data in your database, as that code is taken - working - from my test site.

Check your insert code - I just looked at it and it is very, very bad practice: SQL Injection Attack heaven as well as unlikely to work.

Replace the code with a Parametrized INSERT using SqlCommand.Parameters.AddWithValue for all database fields and you will be both Bobby Tables proof, and inserting the right data to your DB...
 
Share this answer
 
v2
Comments
yogesh a sharma 8-Aug-11 15:17pm    
thanks for reply but it also does't work. the same problem exists.
OriginalGriff 8-Aug-11 15:24pm    
Answer updated
Tech Code Freak 9-Aug-11 0:11am    
My 5!
yogesh a sharma 9-Aug-11 1:01am    
thankssssssssssssss, orriginalgriff very much sir your suggestion did my job.. it was the problem of storing in wrong forma.. because of not using parameters in sql query's.. thanks very much..............And sorry for using capitalization as iam new to this community.thanks once again........

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