2

データベースから画像を表示する際に助けが必要です。ハンドラーを使用してデータベースからハンドラーに画像をロードするのが効率的であることを読みました。しかし、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));
    }

助けてください!ありがとう!

4

1 に答える 1

2

あなたはいくつかのまともな一般的な考えを持っていますが、全体的な構造が欠けています。最善の策は、ハンドラーを使用することですが、成功関数でハンドラーを参照します。例:

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を誤ってエンコード/解釈し、画像を破損している可能性があります。

于 2012-07-10T18:23:13.453 に答える