Using javascript/jquery on file input field

218 Views Asked by At

I have a form with mulitiple file select. I just want send the each file to server via AJAX(selected via multiple select).

I can get the files using

document.getElementById('attachment_file').files

I want to use something like

var files = document.getElementById("attachment_file").files
$.each(files, function(index, file11){
       $.ajax({
        url: "/users",
        type: 'POST',
        dataType: 'json',
        data: {doc: {title: file11}},
        async: false,
        success: function() {
        }

      });
});

Here I'm not able to pass the file params. any suggesstions

4

There are 4 best solutions below

0
On

AFAIK files are not allowed to be sent to the server via AJAX due to security constraints. Different libraries handle this issue differently - refer to your library docs.

0
On

you are not allowed to upload files with plain ajax, typical workarounds either involve flash or the (ab)use o iframes. https://github.com/blueimp/jQuery-File-Upload should be a good library to get you started...

0
On
1
On

You can create a FormData object and send that.

https://developer.mozilla.org/en/DOM/XMLHttpRequest/FormData

See the example code here under 'Sending files using a FormData object':

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest