0

I need to encode .zip file in base64 format on client side and send it on server (php). But, i cannot find any solutions for that in javascript.

i try this:

let zipFile = document.getElementById('fileReciever').files[0];
let formData = new FormData();

formData.append('id', btoa('7804044924'));
formData.append('data', btoa(zipFile));

let req = new XMLHttpRequest();
req.open("POST", 'http://localhost/xmlReader/reciever.php');
req.send(formData);

But in this way i getting just bse64 string in $_POST in filed 'data' on server, what converts by base64_decode in string "[object File]", and i getting nothing in $_FILES. How can correct convert .zip data file to base64 string in javascript and send it on server?

1
  • Why encode to base64? Why normal upload? Commented Jul 31, 2020 at 9:15

1 Answer 1

0

You can get base64 of a file this way. Just send the string as you would send out in a POST request. I was able get zip file back from pasting the base64 string on this site.

function previewFile() {
  const file = document.querySelector('input[type=file]').files[0];
  const reader = new FileReader();

  reader.addEventListener("load", function () {
    // convert file to base64 string using reader.result
    document.querySelector('p').innerHTML=reader.result;
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}
<!DOCTYPE html>
<html>
<body>

<p>Base 64 string here. You might want to trim </p>
<input type="file" onchange="previewFile()"><br>

<script>

</script>


</body>
</html>

Not the answer you're looking for? Browse other questions tagged or ask your own question.