2

I know sending $_POST data with jquery is pretty simple, but is it possible to send $_FILES data with jquery. At the moment I am using a HTTPRequest, but if it is possible to use jquery I would prefer it. Thanks.

function upload() {

     var fileInput = $('#file')[0];
     var data = new FormData();

     for(var i = 0; i < fileInput.files.length; ++i){data.append('file[]',fileInput.files[i]);}
     var request = new XMLHttpRequest();

     request.open('POST','upload.php',true);
     request.setRequestHeader('Cache-Control','no-cache');
     request.onreadystatechange = function() {
  if(request.readyState == 4 && request.status == 200) {

          var return_data = request.responseText;
          alert(return_data);
               if(return_data !== 'success') {
                  failed();
               }else
                if(return_data == 'success') {

                 success();
               }
            }
         }
          request.send(data);
      };
4

2 Answers 2

2

Here is a jQuery version of what you have there

function upload() {
    var fileInput = $('#file')[0];
    var data = new FormData();

    for(var i = 0; i < fileInput.files.length; ++i){
        data.append('file[]',fileInput.files[i]);
    }
    $.ajax({
        type:'POST',
        method:'POST',/* for newest version of jQuery */
        url:'upload.php',
        headers:{'Cache-Control':'no-cache'},
        data:data,
        contentType:false,
        processData:false,
        success: function(response){
            var return_data = response;
            alert(return_data);
            if(return_data !== 'success') {
                 failed();
            }
            else if(return_data == 'success') {
                success();
            }         
        }
    });
}
0
1

No, you will need a form. The way to POST a file to a server is using a FORM with enctype="multipart/form-data". What you can have is forms that are posted to iframes.

1
  • In modern browsers, you can use XHR2! :-)
    – gen_Eric
    Commented Feb 26, 2013 at 16:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.