ThePerplexedOne
ThePerplexedOne

Reputation: 2950

FileReader will only read small files, otherwise returning null

So I'm currently using the following code to read a file as base64:

function getBase64(file) {
    return new Promise(function(resolve, reject) {
        var fr = new FileReader();
        fr.readAsDataURL(file);
        fr.onload = resolve(fr);
  });
}

Now whenever I load in a file above a certain size (unsure of what it is), it returns null for fr.result.

This doesn't seem to be an issue in Google Chrome, though. It will return base64 for any file size. I'm currently testing it with Microsoft Edge.

Upvotes: 0

Views: 87

Answers (1)

phuzi
phuzi

Reputation: 13060

resolve(fr) is being evaluated synchronously and should be wrapped in a function. You are still seeing a little bit of data because readAsDataURL is running asynchronously and has already managed to read some data before resolve(fr) is called.

You should probably register the handler before starting to read the files too.

function getBase64(file) {
    return new Promise(function(resolve, reject) {
        var fr = new FileReader();
        fr.onload = function() { resolve(fr); };
        fr.readAsDataURL(file);
  });
}

Upvotes: 1

Related Questions