脚本运行正常,我正在使用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";
}
}
也许先尝试xfr.open,然后再尝试xfr.onload