简体   繁体   中英

Convert file to Base64

So I am trying to convert a file from tag. This is how my javascript code looks like:

var file = document.getElementById("file").files[0];
if (file) {
  var filereader = new FileReader();
  filereader.readAsDataURL(file);
  filereader.onload = function (evt) {
    var base64 = evt.target.result;
  }
}

That returns undefined .

I think you have missed the return statement in the code. Replace your function with the following lines:

var file = document.getElementById("file").files[0];
if (file) {
  var filereader = new FileReader();
  filereader.readAsDataURL(file);
  filereader.onload = function (evt) {
     var base64 = evt.target.result;
      return base64
  }

}

two little helper and an example.

const blobToDataUrl = blob => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.onload = () => resolve(reader.result);
  reader.onerror = reject;
  reader.readAsDataURL(blob);
});

const blobToBase64 = blob => blobToDataUrl(blob).then(text => text.slice(text.indexOf(",")));

for(let file of document.getElementById("file").files) {
  blobToBase64(file).then(base64 => console.log(file, base64));
}

But why the Promises?

Because your next question will be: How do I get the base64 string out of onload? and the short answer is You don't . A longer answer would be: It's like asking how to get something from the future into the now. You can't. It's like asking how to get something from the future into the now. You can't.

Promises are placeholder/wrapper for values that will eventually be available; but not yet . And they are the foundation of async functions .

So let's skip messing with callbacks and get right to the point where you write

for(let file of document.getElementById("file").files) {
  const base64 = await blobToBase64(file);
  console.log(file, base64);
}

but for that you will have to brush up on async and await .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM