【发布时间】:2021-01-17 20:15:01
【问题描述】:
我正在尝试使用 XMLHttpRequest() 函数上传文件以运行 php 脚本。 这是HTML代码
<form enctype="multipart/form-data" action="testupload.php" method="POST">
<input type="text" class="form-control input-lg" name="image_text" id="filename">
<input type="hidden" name="MAX_FILE_SIZE" value="51200000000" />
Send this file: <input name="usrfile" type="file" />
<input type="button" value="Send File" onclick="uploadtest()"/>
</form>
这里是javascript代码
function uploadtest(){
var file2 =document.getElementById("filename").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xmlhttp.open("GET", "testupload.php?fileID=" + file2 , true);
xmlhttp.send();
}
这是我的 PHP 脚本
<?php
/if(!empty($_FILES['usrfile'])){
// print_r($_FILES);
// echo "goda";
// // File upload configuration
$targetDir = "C:/wamp64/www/CMS_TEST2/uploads/";
$allowTypes = array('mp4', 'jpg', 'png', 'jpeg', 'gif');
// $fileName = basename($_FILES['file']['name']);
$fileName = $_GET["fileID"];
// $fileName = "MCCT0001";
$temp = explode(".", $_FILES["usrfile"]["name"]);
$newfilename = $fileName.".".end($temp);
$targetFilePath = $targetDir.$newfilename;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES['usrfile']['tmp_name'], $targetFilePath)){
echo "File is valid, and was successfully uploaded.\n";
print_r($_FILES);
}
}
//}
?>
如果我使用 PHP isset 表单提交调用 php 脚本。文件上传工作。但是当我使用 ajax $_FILES 调用 php 脚本时的问题返回空。你能帮我解决我在这里做错的事情吗
【问题讨论】:
-
尝试使用 JSON 编码
echo json_encode( array("file"=>$_FILES))发送响应并检查是否收到响应。 -
你得到的是文件名而不是文件本身。这可能会帮助你。 stackoverflow.com/a/23981045/5900189
-
您可以通过检查页面来检查您的 ajax 在 chrome 控制台上是否正常工作。
-
ajax 正在工作,因为我可以看到所有回显响应都在页面控制台中打印
标签: javascript php ajax file-upload