How to convert file to base64 in JavaScript?

前端 未结 7 1930
醉话见心
醉话见心 2020-11-22 06:34

Now I\'m getting File object by this line:

file = document.querySelector(\'#files > input[type=\"file\"]\').files[0]

I need to send thi

7条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 07:01

    Building up on Dmitri Pavlutin and joshua.paling answers, here's an extended version that extracts the base64 content (removes the metadata at the beginning) and also ensures padding is done correctly.

    function getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          let encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
          if ((encoded.length % 4) > 0) {
            encoded += '='.repeat(4 - (encoded.length % 4));
          }
          resolve(encoded);
        };
        reader.onerror = error => reject(error);
      });
    }
    

提交回复
热议问题