Search code examples
javascriptxmlhttprequestfilereaderdata-uri

Why can't my filereader read this data url from a xmlhttprequest


    let MY_URL = "*"
    let DataURL;

    // basic JS way of getting the info from S3
    let request = new XMLHttpRequest();
    request.open('GET', MY_URL, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload =  function(e){
            DataURL = e.target.result;
        };
    };
    request.send();

    listenGetImageLoad(DataURL);

Here I am getting the Data URL of a file I am getting from the web. Next I want to Read it into a fileReader, but I keep getting the bug:

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

My code for the fileReader is as follows::

const listenGetImageLoad = (DataURL) => {

    const imageArray = Object.keys(images)

    let async = imageArray.length

    for (let image in images) {
        const reader = new FileReader()

        reader.addEventListener("load", () => {
            const imageObject = new Image()

            imageObject.addEventListener("load", (event) => {...})

        reader.readAsDataURL(DataURL)
    }
}

This function seems to be failing at reader.readAsDataURL(DataURL). I have no idea as to why this is the case. I am so sure that I have inputted a data URL into the FileReader function too.


Solution

  • You have two problems

    1. You are calling listenGetImageLoad at the wrong time. XMLHttpRequest is async. So you need to call that inside your onload event.

    2. Even when you correct the async issue you are passing the wrong thing to readAsDataURL(). It expects a blob or file object to be passed to it, not a string which is what a data url is.

    Call listenGetImageLoad inside the load event passing in the response from the request to fix your issue.

    request.onload = function() {
      listenGetImageLoad(request.response);
    };
    

    Note you do not need to use readAsDataURL to show an image from a blob. Just call URL.createObjectURL() passing in the blob/file to get a url the browser will be able to load. Then set the src of the image with that url.

    request.onload = function() {
      var url = URL.createObjectURL(request.response);
      yourImage.src = url;
    };