all
I got the binary data of the image(use xhr),let's name this binary data as data
I wonder how to convert data to a real img tags
At first:
I try using FileReder to readAsBinaryString,but It won't work cause reader.onloadend won't fire
Are there other ways to get this done?
Thanks in advance~
$.ajax({
url:src,
type:"GET",
success:function(data){
var reader=new FileReader()
reader.onload=function(e){
var data=e.target.result
console.log(data)
}
reader.readAsDataURL(data)
...
You should probably call readAsDataURL
and use the load
event instead.
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image();
img.src = e.target.result;
};
reader.readAsDataURL(file);
Base64 encode your binary data. See this question on how to base64 binary data in JavaScript.
Then insert the base64 string directly into your image tag. For example, if the binary data is a JPG image, you could do this (in theory):
$.ajax({
url:src,
type:"GET",
success:function(binaryData) {
//toBase64 is a made up function, see above
var base64Data = toBase64(binaryData);
//assuming img is defined outside of here (not in the scope of this question)
img.src = "data:image/jpg;base64," + base64Data;
}
});