6

I have a form with several inputs and other field.

I have a save button, and when I click, I send the form with ajax with jQuery :

$.ajax({
        type:       "POST",
        dataType:   "json",
        url:        $('#ajaxUrl').val(),
        data:       "action=save&" + form.serialize()
});

So, when I have only simple input like text, select etc.. it's ok. But if I have an input type file, I can't retrieve my file. $_FILES is always empty.

How can I do that as simply as possible ?

Edit : I don't want to use a plugin :)

Clément Andraud
  • 9,103
  • 25
  • 80
  • 158
  • Using [formData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) ! – adeneo Jul 18 '13 at 08:34
  • 3
    possible duplicate of [How can I upload files asynchronously with jQuery?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery) – Martijn Jul 18 '13 at 08:39
  • @Clément Andraud, not sure, whether this will help you out or not, But please have a look at http://wordpress.stackexchange.com/questions/71170/how-do-i-upload-import-form-input-files-via-ajax-function You may get some idea. – RONE Jul 18 '13 at 08:56

5 Answers5

3

Implementation for ASP.NET MVC:

To start making your form-wrapper :

<form id="inputform">
    <input class="hide" type="file" name="file" id="file" />
</form>

Сreate a client-handler to send:

$("#yourButton").bind('click', function () {
    var data = new window.FormData($('#inputform')[0]);
    $.ajax({
        xhr: function () {  
            return $.ajaxSettings.xhr();
        },
        type: "POST",
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        url: "@Url.Action("MethodName", "ControllerName")",
        success: function () { },
        error: function () { },
    });
});

Do handler on the server side (controller):

    public ActionResult MethodName(HttpPostedFileWrapper file) {
    var img = Image.FromStream(file.InputStream);
       ....
       return ..;
    }

I hope this will help you save time ;)

HuckFin.7b
  • 325
  • 4
  • 13
1

form.serialize does not manage file inputs. You'll have to an XMLHttpRequest with formData as adeneo suggests, see example usage here. For older browsers, there are solutions using iframe and POSTing the form with the iframe as target. Some jquery plugins will do all that for you, like, say, JQuery-File-Upload (but plenty of others exist).

Community
  • 1
  • 1
instanceof me
  • 38,520
  • 3
  • 31
  • 40
  • Support for formData start in IE10, that's why i'll suggest too to use a plugin which use iframe for support older browser. +1 – A. Wolff Jul 18 '13 at 08:45
  • Hum, my problem, i work on a custom CMS. The function for save a new content is already write.. So if i can just edit this script and no rewrite all... ^^ – Clément Andraud Jul 18 '13 at 08:52
  • Well if you can drop support of older browsers, you can just edit your script to use formData. If you can't (dropping IE 8 & 9 is pretty drastic), I'm afraid that you're gonna have to go a little further. But some plugins will do all of the heavy-lifting, so it shouldn't be very complicated. – instanceof me Jul 18 '13 at 08:56
  • Do you know a very simplist plugin ? – Clément Andraud Jul 18 '13 at 09:06
  • The one listed by LeftyX seems simple enough – instanceof me Jul 18 '13 at 09:21
0

I've used this jQuery plugin which has capabilities to upload files.

HTML:

<form action="file-echo2.php" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile"><br>
    <input type="submit" value="Upload File to Server">
</form>

Javascrtipt:

$('form').ajaxForm({
    beforeSend: function() {

    },
    uploadProgress: function(event, position, total, percentComplete) {

    },
    success: function() {

    },
    complete: function(xhr) {

    }
});
LeftyX
  • 35,328
  • 21
  • 132
  • 193
0

I found this little "vanilla" framework by querying "Using FormData Objects" on google.

used by:

AJAXSubmit(myForm);

just modify on

function ajaxSuccess (){/*here*/}

if you console.log() the response on ajaxSuccess you could see the data submitted to server. It is on submittedData property.

marlo
  • 6,998
  • 5
  • 28
  • 34
0
# Note - your form tag should have enctype="multipart/form-data"
# Try this

     var xdata = new FormData();
     var files = $('#xfile')[0].files;
     xdata.append('xfile',files[0]);

# This is how you add additional data
# You can loop through this if you have many fields in your form
     xdata.append('action', 'save');

     jQuery.ajax({    
          data:xdata,
          contentType: false,
          processData: false,
          type:"post",
          url:"yourfilename.php" 
     })

# You can retrieve it as
$_FILES['xfile'];
Pratik Mehta
  • 707
  • 8
  • 27