![](/img/trans.png)
[英]how to consume IBM watson conversation api from javascript and C#
[英]Consume a C# API that returns file or byte[] from javascript as image
我有以下代碼返回 C# Web API 中的圖像。 到目前為止一切順利,但我無法將其 map 轉換為圖像。
[HttpPost]
[Route("GetImage")]
[ValidateAntiForgeryToken]
public FileResult GetImage(string name)
{
if (string.IsNullOrEmpty(name)) {
return File("imgs/nodisponible.jpg", "image/jpg");
}
var imagen = REST.GetImage(name);
return new FileContentResult(imagen, "image/jpeg");
}
所以在 javascript 方面我做了:
getimage(word: any): Observable<any> {
return this.http.post<ArrayBuffer>(this.baseUrl + 'library/getimage', word, {
headers: this.headers,
withCredentials: true,
});
}
然后顯示圖像:
const iname = JSON.stringify(this.consultadetalle?.cover_url);
this.dataService.getimage(iname).subscribe((responses) => {
$('#imagencover').attr('src', "data:image/png;base64," + responses);
});
但控制台說:
Http 在解析 https://localhost:44476/library/getimage 時失敗
我該如何解決這個問題?
Update: As I said, I'm using Web API, I don't have the view in C#, only javascript with angular. 在 C# 我只有控制器。
您可能需要先將文件轉換為字節。 我在與您類似的項目中成功地使用了它,將圖像文件轉換為字節數組。
public static byte[] ConverToBytes(HttpPostedFileBase file)
{
var length = file.InputStream.Length; //Length: 103050706
byte[] fileData = null;
using (var binaryReader = new BinaryReader(file.InputStream))
{
fileData = binaryReader.Renter code hereeadBytes(file.ContentLength);
}
return fileData;
}
之后我將該信息加載到 Viewbag 並將其轉換為 Base64
var ImageBytes = ConverToBytes(ImageFromApi);
var displayImage= "data:" + imagePulled.FileType + ";base64," + Convert.ToBase64String(ImageBytes);
ViewBag.FileBytes = displayImage;
然后使用它在視圖中顯示它。
<object data="@ViewBag.FileBytes" id="imageDisplayFrame" style="width:100%; min-height:600px; border:1px solid lightgrey; object-fit:contain;" #zoom="200" frameBorder="1" type="@ViewBag.FileType" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.