File Upload Ajax
Upload files through AJAX
1. Why should I write this article?
The landlord went to Beijing for an interview a few days ago and talked about uploading files via ajax. The interviewer told me that he couldn't, so he discussed it. He wrote this article and hoped to study it with everyone.
2. Text
First, you need to use the FormData object added to HTML5 to upload files using ajax. This object is actually equivalent to a form container. It has a method append ("key", value ), you can dynamically add content to a form in the form of a key-value pair.
Second, you need to set the parameters in $. ajax (). For specific settings, see the code.
Let's talk about the code.
HTML:
<input type="file" name="f1" id="f1" /><input type="button" onclick="upload()" value="upload" multiple/><input type="text" value="hehe" id="t1" name="t1"/>
JavaScript:
1 function upload () {2 var formData = new FormData (); // create a FormData object 3 var fileList =$ ("# f1 "). files; // obtain the file in the file control. The file attribute obtains a fileList 4 formData. append ('aaa', fileList [0]); // put the files in fileList into formData one by one. Note that 5 formData cannot be obtained directly in the fileList background. append ('aaa', fileList [1]); // formData. "key" in append (). If the object is input, you can obtain 6 formData at will. append ('bbb ', $ ("# t1 "). val (); // as an example, put the form data at the same time 7 $. ajax ({8 url: "@ Url. action ("receive", "home") ", // C # Razor, or/home/receive, but not secure 9 data: formData, 10 type: 'post', 11 contentType: false, // both contentType and processData must be set to false. Otherwise, the file cannot be sent until 12 processData: false, // This is done to prevent the browser from automatically converting the data format sent and sent to a string or other 13 success: function (data) {// 14 if (data = "") {15 return false; 16} 17}, 18 error: function (a, B, c) {19 alert ("aaa"); 20} 21}); 22}
Background:
[HttpPost] public ActionResult receive() { HttpPostedFileBase file = Request.Files[0]; var file1 = Request.Form[0]; var bbb = Request.Params["bbb"]; return null; }
Note: Both file and file1 are obtained files, while bbb is obtained value, that is, "hehe"
The landlord wrote his blog for the first time. If you have any mistakes, please give me more advice and learn from me modestly.