Reputation: 11
An image file is sent from ASP.Net MVC using FilePathResult. How can this image be converted into a base64 string at client side (web browser) when http response is received. It is showing data in the raw form in response.data object. I've tried
var blob = new Blob([response.data], { type: 'image/jpeg' });
var reader = new FileReader();
reader.onloadend = function () {
var base64data = reader.result;
console.log(base64data);
}
reader.readAsDataURL(blob);
Upvotes: 0
Views: 2996
Reputation: 37786
When you fetch the binary as text with ajax, browsers will try to parse the character set and change your data.
You must fetch the data as a blob to avoid to tell them not to
function getBase64(blob) {
var blob = xhr.response
var reader = new FileReader();
reader.onload = function () {
var base64data = reader.result;
console.log(base64data);
}
reader.readAsDataURL(blob);
}
var xhr = new XMLHttpRequest()
xhr.open('GET', '/myfile.png', true)
xhr.responseType = 'blob' // get data as blob
xhr.onload = function() {
getBase64(xhr.response)
}
xhr.send()
// or if you are using fetch
fetch('/myfile.png')
.then(function(res) {
res.blob() // get data as blob
.then(getBase64)
})
Upvotes: 2
Reputation: 1686
I hope I am not misunderstood:
Try this script, for the easier ajax I'm using jquery:
$.ajax({
url: 'someImage.png',
type: 'POST',
success: function(r) {
var data = btoa(r);
$('img.photo').attr('src', "data:image/png;base64," + data);
},
});
you can change above code as you need.
Upvotes: 0