1. Overview
In the initial HTTP protocol, there is no feature to upload files. rfc1867 (http://www.ietf.org/rfc/rfc1867.txt) adds this functionality to the HTTP protocol. The browser follows this specification to send a user-specified file to the server. The server then resolves the file according to this specification. Most HTTP servers support this protocol, such as Tomcat (this article uses spring MVC, which is httpservelet to receive requests).
Many blogs online, as well as plugin practices, is to build an IFRAME user without a refresh request, and then build a form for submission. But you can actually submit it directly with JavaScript and Ajax.
2. Front-end implementation
First, you need the input tag of type file, which is used for selecting files, both for mobile phones and for PCs.
Then, when you click on the File Input tab, the Select Files control (which is provided internally by the operating system) pops up.
Finally, it is to submit a form (the enctype of the form must be "Multipart/form-data"), and the purpose of submitting the form is to submit the file to the server. Submit a form with a submit button.
<!DOCTYPE HTML><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title></title><Metaname= "Viewport"content= "Width=device-width, initial-scale=1, user-scalable=0"></Head><Body><formname= "MyForm"enctype= "Multipart/form-data"Action= "Http://localhost/uploadImage"Method=post><inputname= "Userfile1"type= "File"onchange= "upload (this);"></form></Body><Script>functionupload () {varMyForm=document.forms['MyForm'];myform.method= 'POST'; Myform.submit ();}</Script></HTML>
3. Back-end implementations
@RequestMapping (value = "/uploadimage") @ResponseBody PublicString Uploadimage (HttpServletRequest request)throwsIOException {multiparthttpservletrequest multipartrequest=(multiparthttpservletrequest) request; Iterator<String> iterator =Multipartrequest.getfilenames (); String FileName= ""; SimpleDateFormat SDF=NewSimpleDateFormat ("YyyyMMdd"); String dir= "upload/" + Sdf.format (NewDate ()) + "/"; String Realpath= Request.getsession (). Getservletcontext (). Getrealpath ("/"); while(Iterator.hasnext ()) {Multipartfile Multipartfile=Multipartrequest.getfile (Iterator.next ()); if(Multipartfile! =NULL) {String fn=Multipartfile.getoriginalfilename (); String suffix= Fn.substring (Fn.lastindexof ("."))); FileName= dir + utils.getrandomstringbylength (6) +suffix; String Path= Realpath +FileName; Path= Path.replace ("\ \", "/"); File F=NewFile (path); if(!F.mkdirs ()) {F.mkdir (); } Multipartfile.transferto (f); } } returnFileName; }
HTTP upload file Upload image upload http upload principle file Upload principle image upload principle