无法从数据库加载图像

时间:2012-07-11 09:48:41

标签: jquery ajax uploading handlers

我使用ajaxFileUploader和2个处理程序上传和下载文件。

ajaxFileUploader代码:

    $.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代码:

    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代码:

     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");
        }
    }

图像正在数据库上传,但当我尝试加载它并将其附加到我的img标签时,图像标签会显示损坏的图像。我不知道是什么原因或似乎是问题。任何帮助将不胜感激。谢谢!

编辑了几行。仍然没有运气。

1 个答案:

答案 0 :(得分:0)

赞成你的上一句话,试试这个:

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

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;
}