Skip to content

Instantly share code, notes, and snippets.

@juanonsoftware
Last active January 26, 2022 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juanonsoftware/103fec4fa9c5b9e2ab14 to your computer and use it in GitHub Desktop.
Save juanonsoftware/103fec4fa9c5b9e2ab14 to your computer and use it in GitHub Desktop.
Displaying image from webapi using javascript base64
WebAPI
// GET api/values
public dynamic Get()
{
var root = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
var path = Path.Combine(root, "App_Data/Koala.jpg");
var bytes = File.ReadAllBytes(path);
var base64 = Convert.ToBase64String(bytes);
return "data:image/jpeg;base64," + base64;
}
}
JS & HTML
<body>
<script>
//$.ajax({
// url: '//localhost:882/api/values',
// type: "GET",
// success: function (data) {
// //alert(JSON.stringify(data));
// }
//}).done(function (data) {
// alert(JSON.stringify(data));
//});
$.ajax({
url: '//localhost:882/api/image',
type: "GET",
success: function (data) {
$('#testimg').attr('src', data);
$('#testimg').attr('style', 'display: block;');
}
});
</script>
<img id="testimg" src="#" alt="Get from webapi" style="display: none;" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment