我正在使用 JavaScript 从客户端已加载的文档向服务器“WebApi”发出请求。
当服务器收到请求时,它会动态构建位图并将其作为 .png 返回给客户端。
当我在客户端读取响应时,我从 .ajax 请求的数据部分返回的是一个空字符串。
如何使用 WebApi 从服务器读取和请求图像,然后使用从服务器接收到的新图像在客户端设置图像的 src 属性?
--WebApi
public HttpResponseMessage Get(int id)
{
ElevationResponse elev = ElevationHelper.GetElevation(id);
Bitmap canvas = ShopDrawing.Elevation.Elevation.GetShopDrawing(elev, true);
var ms = new MemoryStream();
canvas.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
HttpResponseMessage r = Request.CreateResponse();
r.Content = new StreamContent(ms);
r.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
return r;
}
--客户端
$.ajax(
{
async: true,
url: '/api/drawings?id=' + this.id,
type: 'GET',
contentType: "application/json",
success: function (d, status) {
debugger
}
});
最佳答案
只需将 '/api/drawings?id=' + this.id
指定为图像 src
属性。
在服务器端,您应该在canvas.Save()
之后重置内存流,以便从头开始发送。此外,指定 http Content-Length
header ,以便浏览器在下载时知道总大小:
ms.Position = 0;
r.Content.Headers.ContentLength = ms.Length;
如果不行,直接在浏览器输入url,打开开发者工具查看网络流量。
关于c# - 如何将位图返回给浏览器 WebApi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14762845/