JavaEar 专注于收集分享传播有价值的技术资料

Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'

I am saving blob in database and I want to retrieve them and show them after ajax request become successful.

function specificreadURL(input) {
    console.log(input)
    var reader = new window.FileReader();
    //reader.readAsArrayBuffer(input);
    reader.readAsDataURL(input);//line with error
    reader.onloadend = function() {
        var base64data = reader.result;
        console.log(base64data);
    };

}

My code is above. The input is from ajax success. I tried to print in console to see what input is like. I am getting this in console.

enter image description here

  1. How can I pass blob into readAsDataURL() like above blob

  2. I want to convert blob to base64 so i can use it src in image.

UPDATE

function specificreadURL(input, type) {
    console.log(input)
    var reader = new window.FileReader();
    reader.readAsDataURL(input);
    reader.onloadend = function() {
        var base64data = reader.result;
        console.log(base64data);
    };
}

for (var j = 0; j < bblobfile.length; j++) {
    var blob = new Blob([bblobfile[j].blob], {
        type: bblobfile[j].type
    });
    specificreadURL(blob, bblobfile[j].type);
}

Tried above code it is giving me the correct type but the image file is not showing. I think the conversion has something do to with it.

Any idea is appreciated.

1个回答

    最佳答案
  1. The "input" is a binary string , not a blob.

    If you want get a blob from ajax request just do :

    xhr.responseType = "blob";
    

    But if you want to be compatible with old browsers ( not support XHR2 ) , you need convert it to Uint8Array first .

    var arr = new Uint8Array(input.length);
    for (var i = 0; i < input.length; i++){
        arr[i] = input.charCodeAt(i);
    }
    var blob = new Blob([arr.buffer]);