I've got a problem sending a file to a serverside PHP-script using jQuery's ajax-function.
It's possible to get the File-List with $('#fileinput').attr('files')
but how is it possible to send this Data to the server? The resulting array ($_POST
) on the serverside php-script is 0 (NULL
) when using the file-input.
I know it is possible (though I didn't find any jQuery solutions until now, only Prototye code (http://webreflection.blogspot.com/2009/03/safari-4-multiple-upload-with-progress.html)).
This seems to be relatively new, so please do not mention file upload would be impossible via XHR/Ajax, because it's definitely working.
I need the functionality in Safari 5, FF and Chrome would be nice but are not essential.
My code for now is:
$.ajax({
url: 'php/upload.php',
data: $('#file').attr('files'),
cache: false,
contentType: 'multipart/form-data',
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Look at my code, it does the job for me
If your form is defined in your HTML, it is easier to pass the form into the constructor than it is to iterate and add images.
Older versions of IE do not support FormData ( Full browser support list for FormData is here: https://developer.mozilla.org/en-US/docs/Web/API/FormData).
Either you can use a jquery plugin (For ex, http://malsup.com/jquery/form/#code-samples ) or, you can use IFrame based solution to post multipart form data through ajax: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
Starting with Safari 5/Firefox 4, it’s easiest to use the
FormData
class:So now you have a
FormData
object, ready to be sent along with the XMLHttpRequest.It’s imperative that you set the
contentType
option tofalse
, forcing jQuery not to add aContent-Type
header for you, otherwise, the boundary string will be missing from it. Also, you must leave theprocessData
flag set to false, otherwise, jQuery will try to convert yourFormData
into a string, which will fail.You may now retrieve the file in PHP using:
(There is only one file,
file-0
, unless you specified themultiple
attribute on your file input, in which case, the numbers will increment with each file.)Using the FormData emulation for older browsers
Create FormData from an existing form
Instead of manually iterating the files, the FormData object can also be created with the contents of an existing form object:
Use a PHP native array instead of a counter
Just name your file elements the same and end the name in brackets:
$_FILES['file']
will then be an array containing the file upload fields for every file uploaded. I actually recommend this over my initial solution as it’s simpler to iterate over.I just built this function based on some info I read.
Use it like using
.serialize()
, instead just put.serializefiles();
.Working here in my tests.