AnchovyLegend
AnchovyLegend

Reputation: 12538

File uploads using AJAX / HTML 5

I am trying to use AJAX and HTML5 to handle file uploads from clients computer to a folder on the server.

I am at the point where the user can browse for a file on their machine select it. Clicking the upload button is suppose to execute the script necessary to complete the file upload, this is where I get stuck. I am not sure how to continue coding the functionality of this file upload feature using the upload.php script.

My question is, assuming the folder on the server is called docs. How can I download the selected file by the user to the servers docs folder, after the user clicks on the upload button?

I appreciate any suggestions.

Many thanks in advance!

JQuery

    $.ajax({
        url: 'upload.php',  //server script to process data
        type: 'POST',
        xhr: function() {  // custom xhr
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        success: function(data){
            alert("OK");
            $('body').html(data);
        },
        // Form data
        data: formData,
        //Options to tell JQuery not to process data or worry about content-type
        cache: false,
        contentType: false,
        processData: false

    });

HTML

    <form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
    </form>
    <progress></progress>

Upvotes: 0

Views: 674

Answers (1)

Graham Walters
Graham Walters

Reputation: 2064

I believe this code should work for your setup. Basically it checks if you're uploading something in the first if statement. Then it checks if the file exists in the second statement. And if it doesn't, then it moves the file into an uploads folder.

<?php
if ($_FILES["file"]["name"] != NULL) {
  if (file_exists("upload/" . $_FILES["file"]["name"]))
    echo $_FILES["file"]["name"] . " already exists. ";
  else
    move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);
}
?>

Do remember that the .php script needs the correct permissions as well as whichever folder you're putting it into. I believe 766 should do it.

You should also add an error to your ajax. Please add the following after your success

error : function(XMLHttpRequest, textStatus, errorThrown) {
  console.log('An Ajax error was thrown.');
  console.log(XMLHttpRequest);
  console.log(textStatus);
  console.log(errorThrown);
},

Upvotes: 2

Related Questions