我需要在客戶端以 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 中什么也沒有得到。如何正確地將.zip數據文件轉換為javascript中的base64字符串并將其發送到服務器上?
1 回答

www說
TA貢獻1775條經驗 獲得超8個贊
您可以通過這種方式獲取文件的 base64。只需像在 POST 請求中發送一樣發送字符串即可。
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>
- 1 回答
- 0 關注
- 443 瀏覽
添加回答
舉報
0/150
提交
取消