0

ASP.NETでSystem.Drawingを使用して、ユーザーがフォームに入力した内容に基づいてカスタム画像を生成しています。生成されたこの画像は、サーバー上のディレクトリに保存されます。

(ユーザーがフォームを送信した後)別のページに読み込みアイコンを表示し、カスタム画像が生成されると、読み込みアイコンがサーバーディレクトリの画像に置き換えられます。

ジェネリックハンドラー(.ashx)を使用して、<img />タグ内のJPEGとして画像を表示することをお勧めする方もいらっしゃるかもしれません。しかし、これに関して私が抱えている問題は、ユーザーが画像を右クリックして保存すると、.ashxファイルとして保存されることです。

私が抱えている問題は、ファイルディレクトリに画像が正常に作成された後、ページを更新する方法がわからないことです。

4

1 に答える 1

1

これを実現するにはさまざまな方法がありますが、個人的には次のようにします。まず、画像を生成するフォーム送信 (画像の生成に使用しているデータ) を受け取るハンドラーを作成します (ファイルをサーバーに個人的に保存することはしませんが、必要に応じて)、 JSONを使用してこの文字列を返すためにハンドラーを使用して base64 にエンコードします。

public void ProcessRequest (HttpContext context)
{
    // generate the image from POST / GET data sent to this handler from your form
    Bitmap bmp = GenerateImage(postData);

    // now convert your generated image to a base64 string
    string base64 = string.Empty;
    using (MemoryStream ms = new MemoryStream())
    {
        bmp.Save(ms, ImageFormat.Png);
        base64 = Convert.ToBase64String(ms);
    }

    // now return this base64 string to the caller
    context.Response.ContentType = "application/json";
    string json = "{ \"imageBase64\": \"" + base64 + "\" }";
    context.Response.Write(json);
}

クライアント側では、jQuery を使用してハンドラーに Ajax 呼び出しを行い、フォーム データを POST/GET し、base64 でエンコードされた画像の文字列を取得して、 html タグのsrcプロパティを設定します。img

function postAndRetrieveImage() {
    $.ajax({
        url: "http://server/myhandler.ashx",
        data: jsonDataParsedFromForm,
        dataType: "json",
        type: "POST",
        contentType: "application/json",
        async: true,
        cache: false,
        beforeSend: function() {
            // overlay your "loading..." image or something while you wait
            // for response from the server
        },
        complete: function() {
            // hide your "loading..." image (or whatever it is) as the operation
            // has completed
        },
        success: function(data) {
            var response = jQuery.parseJSON(data.d);

            // set the src attribute of the IMG tag (prefixed with the usual 
            // image stuff) with the base64
            var image = document.getElementById("myImage");
            image.setAttribute("src", "data:image/png;base64," + response.imageBase64);
        },
        error: function() {
            // display error in some way
        }
    });
}

私が言ったように、これを達成する方法はたくさんあるので、このラフな (テストされていない) 例は、私がこれを行う方法の 1 つです。IMGタグがあれば、右クリックで画像を保存することもできます。

これが出発点として役立つことを願っています。

于 2013-01-04T15:32:49.193 に答える