繁体   English   中英

使用 C# API 从 javascript 返回文件或字节 [] 作为图像

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM