专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

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

ins518 2025-06-12 13:16:13 技术文章 14 ℃ 0 评论
<form> 
  <input type="file" id="fileInput">
</form>

<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>
<?php
// 后端php代码
header('Access-Control-Allow-Origin: *');

$img = $_FILES['img'];

if (is_uploaded_file($img['tmp_name'])) {
  move_uploaded_file($img['tmp_name'], './'.$img['name']);
  echo json_encode(['url' => 'http://localhost/'.$img['name']]);
} else {
  echo json_encode(['err' => 'upload image error']);
}

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表