Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8205031
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T08:05:14+00:00 2026-06-07T08:05:14+00:00

I need help in displaying an image from database. I’ve read that it’s efficient

  • 0

I need help in displaying an image from database. I’ve read that it’s efficient to use handlers to load image from database to a handler. But I don’t want to use handlers because I assumed that when you set the imageUrl to a handler, the image will only be loaded upon pageLoad. In my case, I have a existing image present at my img tag, then after uploading, I need to change that image. I used ajaxFileUploader plugin and successfully uploaded and save the image to the database. My problem now is retrieving it.

upon successful jquery ajax call, I will be calling a webmethod using ajax. Here is my code for that:

$.ajaxFileUpload
(
    {
        url: 'AjaxFileUploader.ashx',
        secureuri: false,
        fileElementId: 'uploadControl',
        dataType: 'json',
        data: '{}',
        success: function () {
            $.ajax({

                type: "POST",

                url: "UserProfile.aspx/displayImage",

                data: jsonData,

                contentType: "application/json; charset=utf-8",

                dataType: "json",

                success: function (mydata) {
                }
            });
        },
        error: function () {

        }
    }
)

In my ImageRetrieval, the following codes are present:

    public void ProcessRequest(HttpContext context)
    {
    string userid = context.Request.QueryString["user"];
        DBAccess dbacc = new DBAccess();
        DataTable dt = dbacc.getImage(userid);
        byte[] image = ((byte[])dt.Rows[0]["UserImage"]);
        System.Drawing.Image img = byteArrayToImage(image);

        MemoryStream stream = new MemoryStream();
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
        img.Dispose();
        stream.Position = 0;
        byte[] data = new byte[stream.Length];
        stream.Read(data, 0, (int)stream.Length);
        stream.Dispose();
        context.Response.Clear();
        context.Response.ContentType = "image/jpeg";
        context.Response.BinaryWrite(data);
}

My Byte to Image conversion:

    public Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }

My database access:

    public DataTable getImage(string userid)
    {
        DataTable dtGetImage = new DataTable();

        using (SqlConnection cn = MySqlDataAccess.sqlDataAccess.MySqlConnection())
        {
            using (SqlCommand cmd = MySqlDataAccess.sqlDataAccess.MySqlCommand(cn, CommandType.Text, "SELECT * FROM Images WHERE UserId = @userid"))
            {
                cmd.Parameters.Add("@userid", SqlDbType.NVarChar).Value = userid;

                using (SqlDataAdapter da = MySqlDataAccess.sqlDataAccess.MySqlAdapter(cmd))
                {
                    da.Fill(dtGetImage);
                }
            }
        }

        return dtGetImage;
    }

FileUploader.ashx code:

    public void ProcessRequest(HttpContext context)
    {
       string path = context.Server.MapPath("~/Temp");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            var file = context.Request.Files[0];

            string userid = context.Request.QueryString["user"];

            string fileName;

            if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
            {
                string[] files = file.FileName.Split(new char[] { '\\' });
                fileName = files[files.Length - 1];
            }
            else
            {
                fileName = file.FileName;
            }
            string fileType = file.ContentType;
            string strFileName = fileName;

            int filelength = file.ContentLength;
            byte[] imagebytes = new byte[filelength];
            file.InputStream.Read(imagebytes, 0, filelength);
            DBAccess dbacc = new DBAccess();
            dbacc.saveImage(imagebytes, userid);

            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var result = new { name = file.FileName };
            context.Response.Write(serializer.Serialize(result));
    }

Help please! Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T08:05:17+00:00Added an answer on June 7, 2026 at 8:05 am

    You have some decent general ideas, but the overall structure is lacking. Your best bet is to use a use a handler, but reference the handler in your success function. Example:

    var userId = 'MyUserIdFromSomewhere';
    $.ajaxFileUpload
    (
        {
            url: 'AjaxFileUploader.ashx',
            secureuri: false,
            fileElementId: 'uploadControl',
            dataType: 'json',
            data: '{}',
            success: function () {
                $('.ImageId').attr('src', '/ImageRetrieval.ashx?user=' + userId);
            },
            error: function () {
    
            }
        }
    )
    

    You may want to modify your handler to look more like:

    using System;
    using System.Web;
    using System.Configuration;
    using System.IO;
    using System.Data;
    using System.Data.SqlClient;
    
    public class DisplayImg : IHttpHandler
    {
    
        public void ProcessRequest(HttpContext context)
        {
            Int32 userId;
            if (context.Request.QueryString["userId"] != null)
                userId = Convert.ToInt32(context.Request.QueryString["userId"]);
            else
                throw new ArgumentException("No parameter specified");
    
            context.Response.ContentType = "image/jpeg";
            Stream strm = getImage(userId);
            byte[] buffer = new byte[2048];
            int byteSeq = strm.Read(buffer, 0, 2048);
            //Test File output. IIS_USR *SHOULD* have write access to this path, but if not you may have to grant it
            FileStream fso = new FileStream( Path.Combine(Request.PhysicalApplicationPath, "test.jpg"), FileMode.Create);
    
            while (byteSeq > 0)
            {
                fso.Write(buffer, 0, byteSeq);
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 2048);
            }
    
            fso.Close();
        }
    
        public Stream getImage(string userid)
        {
    
            using (SqlConnection cn = MySqlDataAccess.sqlDataAccess.MySqlConnection())
            {
                using (SqlCommand cmd = MySqlDataAccess.sqlDataAccess.MySqlCommand(cn, CommandType.Text, "SELECT UserImage FROM Images WHERE UserId = @userid"))
                {
                    cmd.Parameters.Add("@userid", SqlDbType.NVarChar).Value = userid;
    
                    object theImg = cmd.ExecuteScalar();
    
                    try
                    {
                        return new MemoryStream((byte[])theImg);
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    

    It’s possible that the DataAdapter is encoding/interpreting the data blob incorrectly and corrupting your image.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need help displaying this image which I'm pulling from a JSON server. JSON
I need help displaying only text from within a file that begins with lets
I need help with displaying images from a MySQL database. What I have is
I need help with displaying images from a MySQL database. What I have is
I need help in displaying my images from the directory images on my public_html
i need to list out data from net in that i have 1 image
I am designing a job rota planner for a company and need help displaying
I need some help revising this. It keeps only displaying 0s as the temp.
Need help writing a script downloads data from google insight using c# this is
need help in error in database pivot. i have table tamed table_score like below:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.