1. Browser-side: Select the picture, submit the form, and send the picture to the server
<form action= "" method= "Post" enctype= "Multipart/form-data" >
<input type= "file" name= "image" >
<input type= "Submit" >
The content that is uploaded is in the request body.
2. Server side:
1) manually obtain the request body, need to resolve manually. Request.getinputstream ()
2) Use servlet3.0
3) third-party tools –apache-commons-fileupload
4) Struts2
@WebServlet ("/fileuploadservlet") @MultipartConfig//indicates support for file upload, otherwise nullpublic class Fileuploadservlet extends Httpser Vlet {private static final long serialversionuid = 1l;protected void doget (HttpServletRequest request, HTTPSERVLETRESP Onse response) throws Servletexception, IOException {//1 normal field String username = Request.getparameter ("Usern Ame "); SYSTEM.OUT.PRINTLN (username); 2 Upload field Part part = Request.getpart ("image"); 2.1 Get the filename//* IE--C:\Users\liangtong\Desktop\heima.txt//* Other browser--Heima.txt String Co Ntentdisposition = Part.getheader ("content-disposition"); System.out.println (contentdisposition); * Intercept file name int start = Contentdisposition.indexof ("filename=") + 10; int end = Contentdisposition.length ()-1; String fileName = contentdisposition.substring (start, end); * Browser compatible--lastIndexOf () if not get return-1 FileName = filename.substring (filename.lastindexof ("\ \") + 1); System.out.printlN (fileName); 2.2 Getting uploaded file contents inputstream is = Part.getinputstream (); 2.3 Write the stream to the server file//* upload directory String dir = This.getservletcontext (). Getrealpath ("/web-inf/upload"); File File = new file (dir, fileName); * Stream to copy fileoutputstream out = new FileOutputStream (file); byte[] buf = new byte[1024]; int len =-1; while (len = Is.read (BUF))! =-1) {out.write (buf, 0, Len); } out.close (); Is.close ();} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcepti On {doget (request, response);}
servlet3.0 File Upload