[英]Converting IRestResponse to “image/jpg” File
我正在嘗試從API中提取圖像,然后通過File()
方法返回DOM。
這是我到目前為止所擁有的。
HomeController.cs
:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ImageFromPath()
{
var client = new RestClient("http://{{MYIPADDRESS}}/cgi-bin/snapshot.cgi?channel0=");
var request = new RestRequest(Method.GET);
request.AddHeader("postman-token", "random-postman-token");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Digest username=\"MYUSERNAME\", realm=\"MYENCRYPTEDPASS\", nonce=\"LONGSTRING\", uri=\"/cgi-bin/snapshot.cgi?channel0\", response=\"RESPONSESTRING\", opaque=\"\"");
IRestResponse response = client.Execute(request);(response.RawBytes);
return File(response, "image/jpg");
}
}
這里唯一的問題是return語句中的錯誤, response
顯示
無法從“ RestSharp.IRestResponse”轉換為“ byte []”
當我從本地文件系統中提取圖像時,它變得更容易並且可以工作,這是我HomeController.cs
工作代碼
public ActionResult ImageFromPath(string path)
{
var ms = new MemoryStream();
using (Bitmap bitmap = new Bitmap(path))
{
var height = bitmap.Size.Height;
var width = bitmap.Size.Width;
bitmap.Save(ms, ImageFormat.Jpeg);
}
ms.Position = 0;
return File(ms, "image/jpg");
}
這是我在前端( Index.cshtml
)中的拉動方式:
<img src="@Url.Action("ImageFromPath", new { path = Request.MapPath("~/img/1.jpg") })" />
這行在這里:
return File(response, "image/jpg");
您正在傳遞的response
類型為IRestResponse
(來自RestSharp的類型)。
為什么內置的MVC File方法知道RestSharp? File()
采用字節數組和字符串MIME type 。
嘗試:
return File(response.RawBytes, "image/jpg");
RawBytes
是HTTP請求的原始響應的字節數組。 如果您的API返回圖像的字節數組,則需要將其傳遞給file方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.