Uploading files via a traditional form form submission: HTML code <form id= "Uploadform" action= http://localhost : 8080/cfjax_rs/rest/file/upload " method= " post " enctype =" Multipart/form-data ">
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 to request it: JS 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 + "&NBSP;: " + 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.
about Formdata and its usage What is Formdata? Let's take a look at the introduction on 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+. See also: Https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/FormData |
Here only shows a way to initialize the Formdata from the form < form Enctype = "Multipart/form-data" method = "POST" name = "FileInfo" > JS code var odata = new formdata (Document.forms.namedItem ("FileInfo " "); odata.append ( "CustomField", "This is some extra data" ); var oreq = new xmlhttprequest (); OReq.open ( "POST") "stash.php" , true ); oreq.onload = function (oevent) { if (oreq.status == 200) { oOutput.innerHTML = "uploaded!" ; } else { oOutput.innerHTML = "error " + oReq.status + " occurred&Nbsp;uploading your file.<br \/> "; } }; oreq.send (oData);
See: https://developer.mozilla.org/zh-CN/docs/Web/Guide/Using_FormData_Objects Use Formdata to make Ajax requests and upload files use jquery here, but older versions of jquery like 1.2 are not supported, preferably with 2.0 or later: HTML code <form id= "Uploadform" > &n