【发布时间】:2020-07-20 22:30:05
【问题描述】:
作为Why is $_FILES[] always empty?的后续行动:
当使用 PhP 通过 AJAX 上传文件时,通常会执行以下操作(我是新手,所以请告诉我是否有更好的方法来做到这一点):
- 有一个包含表单和 javascript 的文件,您可以在其中设置和发送
XMLHttpRequest,例如upload_form.php - 有另一个外部 php 文件来处理上传请求,例如上传.php
我的问题是:
是否可以在外部upload.php 文件中中止XMLHttpRequest?。
想要这样做的原因是,如果文件已经存在于服务器上,我想中止XMLHttpRequest,而不是让用户等到上传完成才能被告知失败。
一些图片来说明问题:
为了夸大问题,我在网络选项卡中限制了速度。
用户上传了一个不存在于服务器uploads目录中的文件:
用户上传确实存在于服务器上 uploads 目录中的文件:
一些代码来说明问题:
upload_form.php:
<!-- enctype and method added on suggestions from previous question -->
<form class="form" id="upload_form" enctype="multipart/form-data" method="POST">
<input type="file" name="file_to_upload" id="file_to_upload"><br>
<input class="button" type="submit" value="Upload">
</form>
<script>
const upload_form = document.getElementById('upload_form');
var file_to_upload = document.getElementById('file_to_upload');
upload_form.addEventListener("submit", upload_file);
function upload_file (e) {
e.preventDefault();
const xhr = new XMLHttpRequest()
xhr.open("POST", "upload.php");
xhr.upload.addEventListener("progress", e => {
const percent = e.lengthComputable ? (e.loaded / e.total) * 100 : 0;
console.log(percent.toFixed(0) + "%");
});
// ================= MAIN PART OF QUESTION ===================
// Can I force this to fire from upload.php if file exists?
xhr.addEventListener("abort", e => {
console.log(e);
});
// ===========================================================
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// update some response area here
}
};
xhr.send(new FormData(upload_form));
}
</script>
上传.php:
<?php
$target_path = "uploads/".basename($_FILES["file_to_upload"]["name"]);
$uploaded_file = $_FILES['file_to_upload']['tmp_name'];
$upload_ok = true;
$errors = [];
// ================= MAIN PART OF QUESTION ==========================
// I want this to cause the abort event to fire on the XMLHttpRequest
if (file_exists($target_path)) {
$upload_ok = false;
array_push($errors, 'The file already exists on the server. Please rename the file and try again.');
}
// ==================================================================
if(!$upload_ok) {
echo 'The file was not uploaded because:<br>';
foreach ($errors as $err) {
echo $err.'<br>';
}
} else {
if(move_uploaded_file($_FILES["file_to_upload"]["tmp_name"], $target_path)) {
echo 'File uploaded successfully';
} else {
echo 'Something went wrong. Please try again.';
}
}
?>
我尝试在 upload_form.php 中检查 readyState 和 status 的不同组合,但这没有帮助。
【问题讨论】:
标签: javascript php ajax file-upload xmlhttprequest