0

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);
8
  • AFAIK, you can use the image directly using the raw base64 image. ex: <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAA............" /> Commented Feb 8, 2018 at 7:37
  • actually, I am misunderstanding with your question. Commented Feb 8, 2018 at 7:38
  • data: "����JFIF��C↵↵↵ ↵%# , #&')*)-0-(0%()(�................" Commented Feb 8, 2018 at 7:59
  • Above mentioned is the raw data received in response object. How can that be converted to base 64 string? Commented Feb 8, 2018 at 8:00
  • I think, this is great example for you: codeproject.com/Articles/201767/… Commented Feb 8, 2018 at 9:35

2 Answers 2

2

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)
  })
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.