using Formdata objects to upload a file with jquery Ajax 664 reads 26857 comments 18 likes 18FormData objects, you can use a series of key-value pairs to simulate a complete form, and then use XMLHttpRequest to send this "Form". Use the Formdata object on the Mozilla Developer website for detailed Formdata object usage instructions. But the upload file part only the bottom XMLHttpRequest object sends the upload request, then how to upload through jquery ajax? This article describes uploading files using the Formdata object with jquery. Use<form>form initialization Formdata object mode upload file HTML code<form id= "Uploadform" enctype= "Multipart/form-data" > <input id= "file" type= "file" name= "file"/> <butt On id= "Upload" type= "button" >upload</button></form>JavaScript code $.ajax ({URL:'/upload ', type:' POST ', Cache:false, Data:NewFormData ($ (' #uploadForm ') [0]), ProcessData:false, ContentType:false}). Done (function(res) {}). Fail (function(res) {}); Here are some points to note: ProcessData is set to false. Because the data value is a Formdata object, you do not need to do the processing. <form> tag Add enctype= "Multipart/form-data"property. The cache is set to False and the upload file does not need to be cached. The contenttype is set to FALSE. Because it is by<form> Formdata object constructed by the form, and the attribute enctype= "Multipart/form-data" has been declared, so this is set to false. After uploading, the server-side code needs to get the file input stream object from the query parameter named file, becauseName= "File" is declared in <input>. If not used<form>the form constructs the Formdata object and how to do it? Uploading the file HTML code using the Formdata Object Add Field Method<div id= "Uploadform" > <input id= "file" type= "file"/> <button id= "Upload" type= "button" >upload</ Button></div> there is no <form> tag, there is no enctype= "Multipart/form-data"property. JavaScript codevarFormData =NewFormData (); Formdata.append (' File ', $ (' #file ') [0].files[0]); $.ajax ({URL:'/upload ', type:' POST ', Cache:false, Data:formdata, ProcessData:false, ContentType:false}). Done (function(res) {}). Fail (function(res) {}); Here are a few: the second parameter of append () should be a file object, which is a $ (' #file ') [0].files[0]. ContentType should also be set to 'false'. From Code $ (' #file ') you can see a <input type= "file" in [0].files[0] >tags can upload multiple files, just<input type= "File" > Add multiple or multiple= "multiple"property. Server-side read files from servlet3.0at the beginning, the uploaded file can be obtained via Request.getpart () or Request.getpars () two interfaces. There is not much to say, please refer to the official website tutorial uploading Files withJava Servlet Technology and example the FileUpload Example application reference
Source: http://www.jianshu.com/p/46e6e03a0d53
15. Uploading Files using Ajax jquery