Currently, we have encountered a requirement that AJAX submits data and uploads files at the same time. It is found that formdata is a useful attribute. Below in MVCCodeIt is really amazing to directly submit form data and uploaded files to a model.
VaRTesttakerui_form = $ ("# testtakerui_form ");
VaR Url = testtakerui_form.attr ('action ');
VaR Form = Document. getelementbyid ("testtakerui_form ")
VaR Fileobj = Document. getelementbyid ("logofile"). files;
VaR Formdata = New Formdata (form );
Formdata. append ("logofile", fileobj );
VaR Xhr;
If (Window. XMLHttpRequest ){
Xhr = New XMLHttpRequest ();
}
Else {
Xhr = New Activexobject ("Microsoft. XMLHTTP ");
}
Xhr. Open ('post', URL, True );
Xhr. onreadystatechange = Function (Response ){
If (Xhr. readystate = 4 ){
If (Xhr. Status = 200 ){
$ ("# Content_5" pai.html (xhr. responsetext );
}
}
};
Xhr. Send (formdata );
The server model directly uploads the file, and the model contains other form attributes.
For more information about formdata, see: https://developer.mozilla.org/en-US/docs/Web/API/FormData
However, formdata is not supported by every browser, as shown below:
Feature |
Chrome |
Firefox (gecko) |
Internet Explorer |
Opera |
Safari |
Basic Support |
7 + |
4.0 (2.0) |
10 + |
12 + |
5 + |
Append with filename |
(Yes) |
22.0 (22.0) |
? |
? |
? |
Therefore, considerOther Upload components:
Http://www.uploadify.com /,
Http://jquery.malsup.com/form,
Http://www.phpletter.com/Demo/AjaxFileUpload-Demo,
Http://www.fyneworks.com/jquery/multiple-file-upload/
You can also Google Uploader and find that there are many components available!