简体   繁体   中英

Uploading Zip File To Server With AJAX

I have a php file which takes a zip file and unpacks it then places it at the desired path on my server.

It works great with a typical form that calls on the php file in the action. I am trying to make this work with AJAX but I have tried every piece of code I can find without any luck.

Is there something here I am missing? Surely this can be done?

Form for uploading the zip file,

<div id="response"></div>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" id="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" onClick="uploadZip()" />
</form>

Current JS - I get no errors, the page actually reloads with my current script..

<script>
function uploadZip() {
formdata = new FormData();

if (formdata) {
  $('.main-content').html('<img src="LoaderIcon.gif" />');
  $.ajax({
    url: "assets/upload-plugin.php",
    type: "POST",
    data: formdata,
    processData: false,
    contentType: false,
    success: function (res){
      document.getElementById("response").innerHTML = res; 

    }
  });
}
}
</script>

php script which handles uploading the zip and unzipping it before placing it on the server.

function rmdir_recursive($dir) {
    foreach(scandir($dir) as $file) {
       if ('.' === $file || '..' === $file) continue;
       if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
       else unlink("$dir/$file");
   }

   rmdir($dir);
}

if($_FILES["zip_file"]["name"]) {
    $filename = $_FILES["zip_file"]["name"];
    $source = $_FILES["zip_file"]["tmp_name"];
    $type = $_FILES["zip_file"]["type"];

    $name = explode(".", $filename);
    $accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
    foreach($accepted_types as $mime_type) {
        if($mime_type == $type) {
            $okay = true;
            break;
        } 
    }

    $continue = strtolower($name[1]) == 'zip' ? true : false;
    if(!$continue) {
        $message = "The file you are trying to upload is not a .zip file. Please try again.";
    }

  /* PHP current path */
  $path = '../plugins/';  // absolute path to the directory where zipper.php is in
  $filenoext = basename ($filename, '.zip');  // absolute path to the directory where zipper.php is in (lowercase)
  $filenoext = basename ($filenoext, '.ZIP');  // absolute path to the directory where zipper.php is in (when uppercase)

  $targetdir = $path . $filenoext; // target directory
  $targetzip = $path . $filename; // target zip file

  /* create directory if not exists', otherwise overwrite */
  /* target directory is same as filename without extension */

  if (is_dir($targetdir))  rmdir_recursive ( $targetdir);


  mkdir($targetdir, 0777);


  /* here it is really happening */

    if(move_uploaded_file($source, $targetzip)) {
        $zip = new ZipArchive();
        $x = $zip->open($targetzip);  // open the zip file to extract
        if ($x === true) {
            $zip->extractTo($targetdir); // place in the directory with same name  
            $zip->close();

            unlink($targetzip);
        }
        $message = "Your .zip file was uploaded and unpacked.";
    } else {    
        $message = "There was a problem with the upload. Please try again.";
    }
}

This php function works great as long as I do this with the form action. So I am sure my problem exist in the AJAX function.

Thanks for any help you can provide.

 formdata = new FormData(); 

You've created a FormData object but you never put any data into it.

The easiest approach is to specify the form:

formdata = new FormData(document.forms[0]);

You also need to stop the submit button from actually submitting the form so that the JS can do something.


A cleaner approach would be to:

  1. Stop using intrinsic event attributes
  2. Use the submit handler for the form
  3. Get the form from the event
 <input type="submit" name="submit" value="Upload" onClick="uploadZip()" /> 

Becomes:

<input type="submit" name="submit" value="Upload">
 function uploadZip() { formdata = new FormData(); 

becomes:

function uploadZip(event) {
    var formdata = new FormData(this);
    // Rest of function
    event.preventDefault();
}

and you add:

jQuery("form").on("submit", uploadZip);

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