0

I want to read a file as a list of bytes and encode it as base64 so I can upload it to a server. I have the code in dart (Flutter) which is this:

String fileString = base64Encode(file.readAsBytesSync());

I want to do this in javascript. I have used this but it doesn't work

  const form = document.getElementById('form');
  const file = document.getElementById('file');
  const courseId = "<?php print($courseId) ?>";
  form.addEventListener('submit', e => {
    e.preventDefault();
    // get file name and type
    var filename = file.files[0].name;
    var filetype = filename.split(".").pop();
    var reader = new FileReader();
    reader.readAsBinaryString(file.files[0]);

    reader.onload = function (){
      // filestring = btoa(reader.result);
      console.log(reader.result);
    }
    //base64 encode
    var filestring = btoa(reader.result);


    const formData = new FormData();
    formData.append("action", "uploadFile");
    formData.append("file", filestring.toString());
    formData.append("name", filename.toString());
    formData.append("type", filetype.toString());
    formData.append("courseId", courseId);

     fetch('upload.php', {
       method: 'POST',
       body: formData
     }).then(response => {
       console.log(response);
     }).catch(console.error);

  });
Hawkar Shwany
  • 324
  • 3
  • 15
  • `readAsBinaryString` is asynchronous. It looks like you are using `reader.result` before it resolves. – terrymorse Apr 21 '20 at 18:55
  • Note that `readAsArrayBuffer` is preferred over `readAsBinaryString` for all browsers that support it. Also, the code after `//base64 encode` should be within the `onload` event handler, as @terrymorse suggests. Finally, you'd probably have a better time of it just using [`readAsDataURL`](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL) and chopping off the unnecessary parts (which is captured in the first Note on that page). – Heretic Monkey Apr 21 '20 at 19:03
  • Thank you very much. Your answers helped a lot. – Hawkar Shwany Apr 22 '20 at 07:50

0 Answers0