Using Ajax serialize () forms for serialization to upload files, use Formdata for AJAX requests
Upload files by using a traditional form form submission:
The code is as follows |
Copy Code |
<form id= "Uploadform" action=/cfjax_rs/rest/file/upload "method=" post "enctype =" Multipart/form-data ">
<p > Specify filename: <input type = "text" name= "filename"/></p> <p > Uploading files: <input type = "File" name= "file"/></p> <p > Keyword 1: <input type = "text" name= "keyword"/></p> <p > Keyword 2: <input type = "text" name= "keyword"/></p> <p > Keyword 3: <input type = "text" name= "keyword"/></p> <input type = "Submit" value= "Upload"/> </form> |
Serialize () Serialization of form forms
However, traditional form form submissions can cause page refreshes, but in some cases we do not want the page to be refreshed, and we are using Ajax as a way to request:
code is as follows |
copy code |
$.ajax ({ URL:" Http://localhost:8080/STS /rest/user ", Type:" POST ", Data: $ (' #postForm ') ). Serialize (), success:function (data) { $ (' #serverResponse '). HTML (data); }, error:function (data) { $ (' #serverResponse '). HTML (data.status + ":" + Data.statustext + ":" + data.responsetext); ; } }); |
As above, through $ (' #postForm '). Serialize () can serialize form forms so that all parameters in form forms are passed to the service side.
But the above way, can only pass the general parameter, the file stream of the uploading file cannot be serialized and passed.
But now mainstream browsers are starting to support an object called Formdata, and with this formdata we can easily upload files using Ajax.
What is Formdata? Let's take a look at the introduction from Mozilla.
XMLHttpRequest Level 2 Adds a new interface formdata. Using the Formdata object, we can simulate a series of form controls using JavaScript with some key-value pairs, and we can also use the XMLHttpRequest send () method to commit the "form" asynchronously. The great advantage of using formdata is that we can upload a binary file asynchronously compared to ordinary Ajax.
Newer versions of all major browsers already support this object, such as Chrome 7+, Firefox 4+, IE 10+, Opera 12+, Safari 5+.
Use Formdata to make Ajax requests and upload files
The code is as follows |
Copy Code |
<form id= "Uploadform" > <p > Specify filename: <input type= "text" name= "filename" value= ""/></p > <p > Uploading files: <input type= "file" name= "file"/></p> <input type= "button" value= "Upload" onclick= "doupload ()"/> </form> function Doupload () { var formData = new FormData ($ ("#uploadForm") [0]); $.ajax ({ URL: ' Http://localhost:8080/cfJAX_RS/rest/file/upload ', Type: ' POST ', Data:formdata, Async:false, Cache:false, Contenttype:false, Processdata:false, Success:function (returndata) { alert (returndata); }, Error:function (returndata) { alert (returndata); } }); } |