I'm obtaining an image from Google Charts by making a WebRequest
via POST
.
The problem I'm having is displaying the image returned by Google.
I can see in Fiddler that the request for the image is made, and the image returned in the response when I do:
var response = request.GetResponse();
However from here I don't seem to be able to output the image from my controller.
Here's what I'm doing right now开发者_JAVA百科:
using (var dataStream = response.GetResponseStream())
{
if (dataStream == null) return;
using (var reader = new StreamReader(dataStream))
{
byte[] dataBytes = Encoding.UTF8.GetBytes(reader.ReadToEnd());
Response.ContentType = "image/png";
Response.BinaryWrite(dataBytes);
}
}
The error message displayed in my browser window is:
The image “[path to image]” cannot be displayed, because it contains errors.
Try using a WebClient, it will simplify your code:
public ActionResult MyChart()
{
using (var client = new WebClient())
{
var data = client.DownloadData("http://......");
// TODO: the MIME type might need adjustment
return File(data, "image/png", "chart.png");
}
}
or if you need to use a POST request and send some values use the UploadValues method:
public ActionResult MyChart()
{
using (var client = new WebClient())
{
var request = new NameValueCollection
{
{ "foo", "foo value" },
{ "bar", "bar value" },
};
var data = client.UploadValues("http://......", request);
// TODO: the MIME type might need adjustment
return File(data, "image/png", "chart.png");
}
}
and then in the view:
<img src="@Url.Action("MyChart", "SomeController")" alt="chart" />
or if the url is static and could be reached with a GET request you could directly include it in your view (you don't need a controller action in this case):
<img src="http://......" alt="chart" />
精彩评论