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.
JavaScript
x
12
12
1
[HttpPost]
2
[Route("GetImage")]
3
[ValidateAntiForgeryToken]
4
public FileResult GetImage(string name)
5
{
6
if (string.IsNullOrEmpty(name)) {
7
return File("imgs/nodisponible.jpg", "image/jpg");
8
}
9
var imagen = REST.GetImage(name);
10
return new FileContentResult(imagen, "image/jpeg");
11
}
12
So on the javascript side I made:
JavaScript
1
7
1
getimage(word: any): Observable<any> {
2
return this.http.post<ArrayBuffer>(this.baseUrl + 'library/getimage', word, {
3
headers: this.headers,
4
withCredentials: true,
5
});
6
}
7
and then to show the image:
JavaScript
1
5
1
const iname = JSON.stringify(this.consultadetalle?.cover_url);
2
this.dataService.getimage(iname).subscribe((responses) => {
3
$('#imagencover').attr('src', "data:image/png;base64," + responses);
4
});
5
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.
JavaScript
1
11
11
1
public static byte[] ConverToBytes(HttpPostedFileBase file)
2
{
3
var length = file.InputStream.Length; //Length: 103050706
4
byte[] fileData = null;
5
using (var binaryReader = new BinaryReader(file.InputStream))
6
{
7
fileData = binaryReader.Renter code hereeadBytes(file.ContentLength);
8
}
9
return fileData;
10
}
11
after which I loaded that information into a Viewbag and converted that to Base64
JavaScript
1
4
1
var ImageBytes = ConverToBytes(ImageFromApi);
2
var displayImage= "data:" + imagePulled.FileType + ";base64," + Convert.ToBase64String(ImageBytes);
3
ViewBag.FileBytes = displayImage;
4
then displayed it in a view using this.
JavaScript
1
2
1
<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" />
2