1

I have a file upload and download using ajaxFileUploader and 2 handlers.

ajaxFileUploader code:

    $.ajaxFileUpload
    (
        {
            url: 'AjaxFileUploader.ashx?user=' + userId,
            secureuri: false,
            fileElementId: 'uploadControl',
            dataType: 'json',
            data: '{}',
            success: function (mydata) {

                alert("Image Successfully Uploaded");

                $('#imgdefaultphoto').attr('src', 'ImageRetrieval.ashx?user=' + userId);
            },
            error: function () {

            }
        }
    )

AjaxFileUploader.ashx code:

    public void ProcessRequest(HttpContext context)
    {

        if (context.Request.Files.Count > 0)
        {
            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));

        }

ImageRetrieval.ashx code:

     public void ProcessRequest(HttpContext context)
    {

        string userId = HttpContext.Current.Request.QueryString["user"];

        if (userId != null)
        {
            DBAccess dbacc = new DBAccess();

            DataTable dt = dbacc.getImage(userId);

            context.Response.ContentType = "image/png";

            context.Response.BinaryWrite((byte[])dt.Rows[0]["UserImage"]);

            context.Response.Flush();
        }
        else
        {
            context.Response.Write("No Image Found");
        }
    }

The image is being upload at the database but when I try to load it and append it to my img tag, the image tag shows broken Image. I don't know what causes or seems to be the problem. Any help will be appreciated. Thanks!

Edited some lines. Still no luck.

Luke Villanueva
  • 2,030
  • 8
  • 44
  • 94
  • Code looks okay to me, can you verify whats happening in ajax call F12 in chrome, do you get the correct result there and use context.Response.Flush(); after binary write. – SSA Jul 11 '12 at 10:13
  • Oops! Forgot to do f12. I got some errors. Failed to load resource: the server responded with a status of 404 (Not Found). The name of the handler is in conflict with the .attr src. Changed it but still same error. – Luke Villanueva Jul 11 '12 at 10:37
  • Then you handler is not registered. – SSA Jul 11 '12 at 10:38
  • What do you mean not registered? – Luke Villanueva Jul 11 '12 at 10:40
  • Finally. I recreated the handler and it worked but I have a conversion error. Failed to convert parameter value from a String to a Byte[]. What seems to be the problem? – Luke Villanueva Jul 11 '12 at 10:52
  • you need to convert the string to a Byte array. – rlemon Jul 11 '12 at 12:03
  • Hey! Did you get a chance to fix this issue?! I have the same problem and wondering if you can help me!! Thank you!! :-) – challengeAccepted Nov 04 '13 at 21:37

1 Answers1

0

BAsed on your last remark try this:

var img = dt.Rows[0]["UserImage"];
byte[] imagebytes = img.ToArray();
context.Response.BinaryWrite(imagebytes);

or

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}
SSA
  • 5,433
  • 4
  • 36
  • 50