将从数据库检索的图像显示到图像控件

时间:2012-07-10 18:11:43

标签: jquery asp.net image download

我需要帮助才能显示数据库中的图像。我已经读过使用处理程序将图像从数据库加载到处理程序是有效的。但是我不想使用处理程序,因为我假设当你将imageUrl设置为处理程序时,图像只会在pageLoad上加载。在我的情况下,我的img标签上有一个现有的图像,然后在上传后,我需要更改该图像。我使用了ajaxFileUploader插件并成功上传并将图像保存到数据库中。我现在的问题是检索它。

成功进行jquery ajax调用后,我将使用ajax调用web方法。这是我的代码:

$.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 () {

        }
    }
)

在我的ImageRetrieval中,存在以下代码:

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

我的字节到图片转换:

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

我的数据库访问:

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

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

请帮忙!谢谢!

1 个答案:

答案 0 :(得分:2)

你有一些不错的一般想法,但整体结构缺乏。最好的办法是使用use a handler,但在成功函数中引用处理程序。例如:

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 () {

        }
    }
)

您可能希望将处理程序修改为更像:

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

DataAdapter可能会错误地编码/解释数据blob并破坏您的图像。