简体   繁体   中英

How to upload files with Ajax to php script with XAMPP

I have tried every proposed solution for last 3 hours and none worked for me. Please keep in mind that I am very new to ajax.

Here is my ajax code:

 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);
   }
 });

Here is the piece of form (it's last form attribute which is disabled by default):

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

And here is php class which should retrieve this file:

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
        ));
}

When I try to log messages into separate file php code seems to be working but I cannot find the file in any of xampp folders. Additionally the alert(data); from ajax does not show any value.

You should move the file first to some folder by calling 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");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM