如何使用 Ajax 将文件上传到 php 脚本 XAMPP

How to upload files with Ajax to php script with XAMPP

我在过去 3 小时内尝试了所有建议的解决方案,none 对我有效。请记住,我是 ajax.

的新手

这是我的 ajax 代码:

 var formData = new FormData();
formData.append('file', $('#commercialAnimation')[0].files[0]);


$.ajax({

url : 'includes/upload.php',
   type : 'POST',
   data : formData,
   processData: false,  // tell jQuery not to process the data
   contentType: false,  // tell jQuery not to set contentType
   success : function(data) {
       console.log(data);
       alert(data);
   }
 });

这是表单的一部分(它是默认禁用的最后一个表单属性):

<label id="uploadAnimation">Upload your file:</label>
<input type="file" id="myfile" disabled>

这是 php class 应该检索此文件:

include 'db_connector.php';
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
//file uploaded
}else{
//error while uploading

  echo json_encode(array(
           'error' => true,
           'message' => $message
        ));
}

当我尝试将消息记录到单独的文件中时 php 代码似乎可以正常工作,但我无法在任何 xampp 文件夹中找到该文件。 此外,ajax 中的 alert(data); 不显示任何值。

您应该先将文件移动到某个文件夹,方法是调用 move_uploaded_file:

   if ($fileError == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES['file']['tmp_name'];
        $name = $_FILES['file']['name'];
        move_uploaded_file($tmp_name, "$your_uploads_dir/$name");
    }