【问题标题】:How to encode .zip file to base64 in javascript? [duplicate]如何在javascript中将.zip文件编码为base64? [复制]
【发布时间】:2020-07-31 09:07:48
【问题描述】:

我需要在客户端以 base64 格式编码 .zip 文件并将其发送到服务器 (php)。但是,我在 javascript 中找不到任何解决方案。

我试试这个:

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);

但是通过这种方式,我在服务器上归档的“数据”中获得了 $_POST 中的 bse64 字符串,通过字符串“[object File]”中的 base64_decode 进行转换,而我在 $_FILES 中一无所获。如何在javascript中正确将.zip数据文件转换为base64字符串并发送到服务器上?

【问题讨论】:

  • 为什么要编码为base64?为什么正常上传?

标签: javascript php base64


【解决方案1】:

您可以通过这种方式获取文件的 base64。只需像在 POST 请求中一样发送字符串即可。 我可以通过在this site 上粘贴 base64 字符串来获取 zip 文件。

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>

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多