Rendering image(stream object) using jquery

那年仲夏 提交于 2019-12-08 09:03:44

问题


Just wondering, how can I bind an image (stream) returned by an action method in an ajax call to an image element using jquery.

JavaScript:

$(document).ready($(function () {
        $(':input').change(function () {

                // object
                var Person = {
                            Name: 'Scott',
                            Address: 'Redmond'
                        };
                // Function for invoking the action method and binding the stream back
                ShowImage(Person);
    });
}));

 function ShowImage(Person) {


        $.ajax({
            url: '/Person/GetPersonImage',
            type: "Post",
            data: JSON.stringify(Person),
            datatype: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {

                // idImgPerson is the id of the image tag
                $('#idImgPerson')
                   .attr("src", data);

            },
            error: function () {
                alert('Error');
            }
        });

Action method:

  public FileContentResult GetPersonImage(Person person)
        {

            // Get the image    
            byte[] myByte = SomeCompnent.GetPersonImage(person);
            return File(myByte, "image/png");

        }

Problem:

The Action method is returning the stream, but it is not getting rendered on the page. I am I missing some thing here...

Thanks for looking in to it.


回答1:


So I was working on this today and ran into your question, which helped (and hurt) me. Here is what I found:

  1. Like Eben mentioned you cant have the json data type. but thats only part of the problem. When you try to $('#idImgPerson').attr("src", data); as in your code you will just set the src attribute to the bytes returned by the call do the GetPersonImage() method.

I ended up using a partial view:

Using the standard mvc3 template

Index.cshtml (excerpt):

<h3>Using jquery ajax with partial views</h3>
<div id="JqueryAjax">
<input class="myButton" data-url='@Url.Action("GetImagesPartial","Home")' name="Button1" type="button" value="button" />

Create the partial view which makes reference to the action that provides the image:

@model string

<div>
<img  id="penguinsImgActionJquery"  alt="Image Missing" width="100" height="100" 
src="@Url.Action("GetPersonImage", "Home", new { someString=Model })" />
<br />
<label>@Model</label>
</div>

HomeController with both action methods:

 public ActionResult GetImagesPartial(string someImageName)
    {

        return PartialView((object)someImageName);
    }

    public FileContentResult GetPersonImage(string someString)
    {

        var file = System.Web.HttpContext.Current.Server.MapPath(localImagesPath + "Penguins.jpg");
        var finfo = new FileInfo(file);
        byte[] myByte = Utilities.FileManagement.FileManager.GetByteArrayFromFile(finfo);
        return File(myByte, "image/png");

    } 

Jquery:

$(document).ready(function () {
$('.myButton').click(function (e) {
    var bleh = $(this).attr("data-url");
    e.preventDefault();
    someData.runAjaxGet(bleh);
});

var someData = {
    someValue: "value",
    counter: 1,
};
someData.runAjaxGet = function (url) {
    _someData = this;
    $.ajax({
        url: url,
        type: "Get",
        data: { someImageName: "ImageFromJQueryAjaxName" + _someData.counter },
        success: function (data) {
            $('#JqueryAjax').append(data);
            _someData.counter = _someData.counter + 1;
        },
        error: function (req, status) {
            alert(req.readyState + " " + req.status + " " + req.responseText);
        }
    });

 };
 });

sorry I know there is a little bit of extra code in the script file i was trying to play with namespaces too. Anyhow, i guess the idea is you request the partial view with ajax, which contains the image rather than requesting the image directly.



来源:https://stackoverflow.com/questions/6033452/rendering-imagestream-object-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!