2

I am trying ajax file upload. I've tried the same script in another proect. It worked properly. But now its not working. On the server side I get 'Null' with var_dump($_FILES["uploadFiles"]); and var_dump($_POST["uploadFiles"]); returns an empty array: array(1) { [0]=>string(0)""}

So I suspect some issues with apache/php configuration.

One of the solution given here discusses about htaccess redirect rules. Here is my htaccess content:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress</code>

Is there any thing wrong with my htaccess content?

If not what else may be the reason for $_FILES to be Null?

My php.ini variables:

post_max_size = 160M
upload_max_filesize = 100M
upload_tmp_dir = "/tmp/"
file_uploads = On 
max_file_uploads = 20

Thanks in Advance for your help.

update:

Response headers of in browser: enter image description here

Here is my code:

  <form class="inputF" id="entry_upload_form" action="" method="post" enctype="multipart/form-data">

        <div class="field_text">
         Attach file:  
        </div>
        <input type="file" name="file1[]" id="file1"> <br>

        <div class="field_text">
         Attach file:  
        </div>
        <input type="file" name="file2[]" id="file2"> <br>

        <div class="field_text">
         Attach file:  
        </div>
        <input type="file" name="file3[]" id="file3"> <br>

        <div class="buttonRow">
          <button class="submit buttons greenButton">Post</button> 
          <button class="reset buttons blueButton">Reset</button>
        </div>
  </form>

part of my jQuery:

var fileSelect = document.getElementById('file1');
    files1 = fileSelect.files;

    if(files1.length != 0) {
        files[i] = fileSelect.files;
        i++;
    }

    fileSelect = document.getElementById('file2');
    files1 = fileSelect.files;

    if(files1.length != 0) {
        files[i] = fileSelect.files;
        i++;
    }

    fileSelect = document.getElementById('file3');
    files1 = fileSelect.files;

    if(files1.length != 0) {
        files[i] = fileSelect.files;
        i++;
    }

    // Create a new FormData object.
    var formData = new FormData();

    // Loop through each of the selected files.
    for (var i = 0; i < files.length; i++) {
      var file = files[i];

      // Add the file to the request.
      formData.append('uploadFiles[]', file, file.name);
    }

    jQuery.ajax({
        url: content_url + '/themes/Karma/entry-portal/ajax_upload.php',  //Server script to process data
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = jQuery.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
        beforeSend: function () {
                //jQuery("#wpboulevard_progressBar").show();
            },
        success: function (response) {
                //jQuery('#wpboulevard_upload_status').html(response);
            },
                //error: errorHandler,
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
//On success
    function completeHandler(){
        jQuery().html('Files uploaded successfully');
    }

    //Progress handling function
    function progressHandlingFunction(e){
        if(e.lengthComputable){
            jQuery('progress').attr({value:e.loaded,max:e.total});
        }
    }
});
Community
  • 1
  • 1
Mr.code892
  • 209
  • 3
  • 16
  • No errors or warnings in logs? /tmp folder accessible? Here is a good check list: http://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php – ficuscr Apr 17 '15 at 18:28
  • Have you watched the request / response in the browser's console? – Jay Blanchard Apr 17 '15 at 18:32
  • 1
    Tried `formData.append('uploadFiles', file);` instead of `formData.append('uploadFiles[]', file, file.name);` ? See https://developer.mozilla.org/en-US/docs/Web/API/FormData#Browser_compatibility – guest271314 Apr 17 '15 at 18:39
  • @JayBlanchard I added the response from the browser's console. Seems to be ok. – Mr.code892 Apr 17 '15 at 18:45
  • 144 bytes and not seeing any request payload in your screen shot. I'm thinking issue is client side JS related. – ficuscr Apr 17 '15 at 18:56
  • @guest271314 I tried your suggestion. $_FILES is null. But var_dump($_POST) shows this: string(17) "[object FileList]" – Mr.code892 Apr 17 '15 at 19:01
  • Agree with guest271314. The method signature looks wrong for `append`. Should be `formData.append(name, value, filename);` – ficuscr Apr 17 '15 at 19:05
  • @ficuscr I can check the variables file and files. They have the 'file' objects. But I dont know how to check whether formData is actually appended with uploaded files. Other than this not sure where I am going wrong. – Mr.code892 Apr 17 '15 at 19:06
  • Other than that nothing jumps out at me. Suppose you could scrap it and look at something like http://www.plupload.com/ - Nice library and would get rid of that arbitrary 3 file inputs approach. Good luck! – ficuscr Apr 17 '15 at 19:10
  • Thanks. I'll try to use a library. – Mr.code892 Apr 17 '15 at 19:14
  • @Mr.code892 Try utitlizing `json` , `data-uri`s to process , upload files; see http://stackoverflow.com/questions/28856729/upload-multiple-image-using-ajax-php-and-jquery/ – guest271314 Apr 17 '15 at 19:35

1 Answers1

1

Change your HTML to this:

<form class="inputF" id="entry_upload_form" enctype="multipart/form-data">
        <div class="field_text">Attach file:</div>
        <input type="file" name="files[]" id="myFiles" multiple> <br>

        <div class="buttonRow">
          <button class="submit buttons greenButton">Post</button> 
          <button class="reset buttons blueButton">Reset</button>
        </div>
  </form>

The HTML changes will allow the user to upload multiple files with only one file input. If you want to limit the user to 3 files only, you can do this on the client side with some javascript or you can do it on the server side with PHP. The user can hold down the CTRL or Shift key to select multiple files to upload at once.

Now change this part of your javascript/jQuery from this:

    var fileSelect = document.getElementById('file1');
    files1 = fileSelect.files;

    if(files1.length != 0) {
        files[i] = fileSelect.files;
        i++;
    }

    fileSelect = document.getElementById('file2');
    files1 = fileSelect.files;

    if(files1.length != 0) {
        files[i] = fileSelect.files;
        i++;
    }

    fileSelect = document.getElementById('file3');
    files1 = fileSelect.files;

    if(files1.length != 0) {
        files[i] = fileSelect.files;
        i++;
    }

    // Create a new FormData object.
    var formData = new FormData();

    // Loop through each of the selected files.
    for (var i = 0; i < files.length; i++) {
      var file = files[i];

      // Add the file to the request.
      formData.append('uploadFiles[]', file, file.name);
    }

To This:

var formData = new FormData();
// Loop through each file attached for upload and append it to formData
$.each($('#myFiles')[0].files, function(i, file) {
    formData.append('uploadFiles['+i+']', file);
});
three3
  • 2,756
  • 14
  • 57
  • 85