2016-01-22 65 views
1

我想建立一个图表使用AJAX调用Web服务。我能够构建图表并将其转换为图像,但出于某种原因,我无法将图像恢复到我的AJAX调用。从asp.net ajax图像webservice

看起来像这样的asp.net web服务方法。

[WebMethod(EnableSession = true)] 
    public void getCandles(string Symbol) 
    {    
     Chart chrt = new Chart(); 

     stockQuotes.bldChart(ref chrt); //// returns chart of candlesticks 

     bytes[] chartBytes; 

     using (var chartimage = new MemoryStream()) //// change chart to bytes 
      { 
       try 
       { 
        chrt.SaveImage(chartimage, ChartImageFormat.Png); 
        chartBytes = chartimage.GetBuffer(); 
       }catch 
       { 
        return (null); 
       } 
      } 

     /// Transform to memory stream and finally to image 
     MemoryStream ms = new MemoryStream(chartImage); 
     Image img = Image.FromStream(ms) 


     /// Build respoonse       
     Context.Response.Clear(); 
     Context.Response.ContentType = "image/png"; 
     index._Stocks[Symbol].ChartImage.Save(Context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);    

    } 

这种方法是通过AJAX调用看起来如下调用:

function UpdatePriceChart() 
    { 
     var selectedSymbol = $("#ddlSymbols").val(); 



     $.ajax({ 
      url: "/WS/wsCandles.asmx/getCandles", 
      data: { "Symbol": $("#ddlSymbols").val() }, 
      method: "post", 
      success: function (data) { 
       $('#chrtPrice').attr('src', data); 
      }, 
      error: function (err) { 
       alert(err); 
      } 

     }) 
    } 

出于某种原因,返回的图像始终是空的。任何人都可以把我引向正确的方向吗?感谢您的帮助。

+0

在jQuery ajax调用中将dataType设置为'image/png'。并且使其成为GEt请求类型而不是POST。 – Sunil

+0

您发送的数据是完整的图像二进制格式,您将其放在要求输入文件名的img的src中,或者嵌入base64图像 – Aristos

回答

0

如果那样,我通常与返回图像回直接到img的src,例如处理程序走,页面部分将是这样的:

function UpdatePriceChart() 
    { 
     var selectedSymbol = $("#ddlSymbols").val(); 

     $('#chrtPrice').attr('src', '/WS/wsCandles.ashx?symbol=' + selectedSymbol); 
    } 

和处理程序将是这样的:

public void ProcessRequest (HttpContext Context) 
{ 
     Chart chrt = new Chart(); 
     stockQuotes.bldChart(ref chrt); //// returns chart of candlesticks 

     bytes[] chartBytes; 

     using (var chartimage = new MemoryStream()) //// change chart to bytes 
      { 
       try 
       { 
        chrt.SaveImage(chartimage, ChartImageFormat.Png); 
        chartBytes = chartimage.GetBuffer(); 
       }catch 
       { 
        return (null); 
       } 
      } 

     /// Transform to memory stream and finally to image 
     MemoryStream ms = new MemoryStream(chartImage); 
     Image img = Image.FromStream(ms) 


     /// Build respoonse       
     Context.Response.ContentType = "image/png"; 
     index._Stocks[Symbol].ChartImage.Save(Context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);    
} 

您需要添加一些额外的代码读取符号,也许一些额外的更改,以期望的工作,但是这是想法。