前端开发-文件上传,如何使用XMLHttpRequest将文件发送到后台?

前端开发-文件上传,如何使用XMLHttpRequest将文件发送到后台?

编码文章call10242025-03-06 11:50:3143A+A-
<script> { const fileInput = document.getElementById('fileInput') fileInput.accept = 'image/*' fileInput.onchange = () => { const file = fileInput.files[0] const formData = new FormData() const xhr = new XMLHttpRequest() formData.append('img', file) xhr.open('POST', 'http://localhost/upload.php', true) xhr.send(formData) xhr.onreadystatechange = () => { if (xhr.readyState !== 4) return if (xhr.status === 200) { const data = JSON.parse(xhr.responseText) const img = new Image() img.src = data.url document.body.appendChild(img) } else { alert('文件上传失败: ' + xhr.status) } } } } </script>
 'http://localhost/'.$img['name']]);
} else {
  echo json_encode(['err' => 'upload image error']);
}

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4