使用jquery渲染图像(流对象)

只是想知道,如何使用jquery将ajax调用中的action方法返回的图像(流)绑定到图像元素。

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

行动方式

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

问题

Action方法返回流,但它没有在页面上呈现。 我在这里错过了一些东西……

感谢您的关注。

所以今天我正在研究这个问题并遇到了你的问题,这对我有帮助(并且伤害了我)。 这是我发现的:

  1. 就像Eben提到的那样,你不能拥有json数据类型。 但这只是问题的一部分。 当你尝试$(’#idImgPerson’)。attr(“src”,data); 在您的代码中,您只需将src属性设置为调用返回的字节执行GetPersonImage()方法。

我最终使用了局部视图:

使用标准的mvc3模板

Index.cshtml(摘录):

 

Using jquery ajax with partial views

创建部分视图,该视图引用提供图像的操作:

 @model string 
Image Missing

HomeController有两种动作方法:

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

抱歉,我知道脚本文件中还有一些额外的代码,我也尝试使用命名空间。 无论如何,我想这个想法是你用ajax请求部分视图,它包含图像而不是直接请求图像。