Skip to content
Advertisement

Consume a C# API that returns file or byte[] from javascript as image

I’ve the following code that returns an image in C# Web API. So far so good but I can’t map it to an image.

    [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");
    }

So on the javascript side I made:

  getimage(word: any): Observable<any> {
    return this.http.post<ArrayBuffer>(this.baseUrl + 'library/getimage', word, {
      headers: this.headers,
      withCredentials: true,
    });
  }

and then to show the image:

 const iname = JSON.stringify(this.consultadetalle?.cover_url);
  this.dataService.getimage(iname).subscribe((responses) => {
    $('#imagencover').attr('src', "data:image/png;base64," + responses);
  });

but the console says:

Http failure during parsing for https://localhost:44476/library/getimage”

How can I solve this?

Update: As I said, I’m using Web API, I don’t have the view in C#, only javascript with angular. In C# I’ve only the controllers.

Advertisement

Answer

You may need to convert the file to bytes first. I successfully used this, in a project similar to yours, to convert the image file to a byte array.

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;
}

after which I loaded that information into a Viewbag and converted that to Base64

var ImageBytes = ConverToBytes(ImageFromApi);         
var displayImage= "data:" + imagePulled.FileType + ";base64," + Convert.ToBase64String(ImageBytes);
                ViewBag.FileBytes = displayImage;

then displayed it in a view using this.

<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" />
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement