Recently there is no time to organize information, a job to understand the business, all day by the business Metrorrhagia.
Summing up today, I got a morning cross-domain asynchronous upload file. The main use of the technology has HTML5 formdata,ajax,spring MVC.
First look at the upload page:
<!DOCTYPE HTML><HTML> <Head> <MetaCharSet= "UTF-8"> <Scripttype= "Text/javascript"src= "Js/plugins/jquery-1.8.3.min.js" ></Script> <title></title> </Head> <Body> <inputtype= "File"ID= "File_upload"/> <inputtype= "button"value= "Upload picture"ID= "Upload"/> </Body> <Scripttype= "Text/javascript"src= "Js/upload.js" ></Script></HTML>
Uploading a page is simple, just two input elements.
Then look at the upload.js. Note that this upload.js is written by himself, and that ajaxfileupload is not the method that jquery provides for uploading plugins.
$ (document). Ready (function(){ functionajaxfileupload () {varFormData =NewFormData (); Formdata.append (' File ', $ ("#file_upload") [0].files[0]);//turn files into binary form$.ajax ({type:"POST", URL:"Http://localhost:8080/nitshareserver/serve/fileupload", Async:false, ContentType:false,//This must be written .ProcessData:false,//This must also be written, or it will be an errorData:formdata, DataType:' Text ',//return type, with json,text,html. There is no JSONP format, so don't be paranoid about using JSONP to do cross-domain. Successfunction(data) {alert (data); }, Error:function(XMLHttpRequest, Textstatus, Errorthrown, data) {alert (errorthrown); } }); } $("#upload"). Click (function() {ajaxfileupload (); });});
Front end so you can, next look at the service side of the wording.
Service-side interface notation:
// @ResponseBody @RequestMapping ( Value= "FileUpload", method=requestmethod.post,produces= "Text/html;charset=utf-8" ) public void Addpic (HttpServletResponse response,httpservletrequest request, @RequestParam (Value = "File", required=< Span style= "color: #0000ff;" >false ) multipartfile file) throws ioexception{System.out.println (File.getoriginalfilename ()); Response.getwriter (). Write ( "Success" ); Response.setheader ( "Access-control-allow-origin", "*" // return "Success"; }
Here Response.setheader ("Access-control-allow-origin", "*"); This sentence is very important, without which the front end receives no data returned. Access-control-allow-origin is a server-side return response header defined in HTML5 that addresses cross-domain permissions issues for resources such as fonts. It defines which domain the resource is allowed to reference, or is referenced by all domains (the Google font uses * to indicate that the font resource is allowed to be referenced by all domains), but it is not used in real products. Here is just a handy demo.
Then run the project, see if the front end will receive success it.
Results:
Server console:
Reprint Annotated Source: http://www.cnblogs.com/BigDreamer/
(H5) Formdata+ajax+springmvc asynchronous upload of files across domains