用php / ajax上传图像正在刷新页面

问题描述 投票:0回答:1

脚本运行正常,我正在使用formData()通过ajax上传图像,并且已正确将其上传到文件夹,但是我不明白为什么在调用move_uploaded_file()后刷新页面的原因在php脚本中。这是完整的代码:

index.html

<label>Add picture?</label>
<input type='file' accept='.png,.gif,.jpg' onchange='upload_img(this)'>

script.js

function upload_img(e) {
  let file = e.files[0];
  let formData = new FormData();
  formData.append('file', file);

  let xhr = new XMLHttpRequest();
  xhr.onload = function () {
    // I want to show a message here but the page is being refreshed
    document.getElementById('ajax_result').innerHTML = xhr.responseText;
  }
  xhr.open("POST", "upload_img.php", true);
  xhr.send(formData);
}

upload_img.php

<?php
  if (!empty($_FILES['file'])) {
    var_dump($_FILES['file']);
    $path = "../img_uploads/";
    $path = $path . basename($_FILES['file']['name']);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
      echo "The file " .  basename($_FILES['file']['name']) . " has been uploaded";
    }
  }
php ajax file-upload image-uploading form-data
1个回答
0
投票

也许先尝试xfr.open,然后再尝试xfr.onload

© www.soinside.com 2019 - 2024. All rights reserved.