1.servlet just add a comment and use Request.getpart to get the value of the file, which is the servlet3.0 API
2. The form needs to add an attribute enctype= "Multipart/form-data"
Now attach the code
Form:
<formMethod= "POST"Action= "Upload"enctype= "Multipart/form-data" >File:<inputtype= "File"name= "File"ID= "File" /> <BR/>Destination:<inputtype= "text"value= "F:"name= "Destination"/> <BR/> <inputtype= "Submit"value= "Upload"name= "Upload"ID= "Upload" />
</form>
Servlet:
Add these two notes to the class's reputation
@WebServlet (name = "Fileuploadservlet", Urlpatterns = {"/upload"})
@MultipartConfig
Custom methods:
The ProcessRequest method is to get the value of the file
protected voidProcessRequest (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8");
Request.setcharacterencoding ("Utf-8");
Get pathFinalString Path = request.getparameter ("Destination");
Get the value of a fileFinalPart Filepart = Request.getpart ("File"); System.out.println (Filepart); FinalString FileName =GetFileName (Filepart); Manipulating files using IO stream outputstream out=NULL; InputStream filecontent=NULL; FinalPrintWriter writer =Response.getwriter (); Try{ out=NewFileOutputStream (NewFile (path +File.separator+fileName)); Filecontent=Filepart.getinputstream (); intRead; Final byte[] bytes =New byte[1024]; while(read = Filecontent.read (bytes))! =-1) {out.write (bytes,0, read); } writer.println ("New file" + FileName + "created at" +path); LOGGER.log (Level.info,"File {0} being uploaded to {1}", Newobject[]{filename, path}); } Catch(FileNotFoundException fne) {writer.println ("You either didn't specify a file to upload or is" + "trying to upload a file to a protected or none Xistent "+" location. "); Writer.println ("<br/> ERROR:" +fne.getmessage ()); LOGGER.log (Level.severe,"Problems during file upload. Error: {0} ", Newobject[]{fne.getmessage ()}); } finally { if(Out! =NULL) {out.close (); } if(Filecontent! =NULL) {filecontent.close (); } if(Writer! =NULL) {writer.close (); } } }
The
GetFileName method is to get the file name
private String getfilename (final Span style= "color: #000000;" > part) { final String partheader = Part.getheader (" Content-disposition "); LOGGER.log (Level.info, part Header = {0} ", Partheader); for (String content:part.getHeader ("Content-disposition"). Split (";" Content.substring (Content.indexof ( ' = ') + 1). Trim (). replace ("\" "," " return null ;}
And finally wrote it in the Dopost method.
protected void DoPost (httpservletrequest request, httpservletresponse response) throws servletexception, IOException {processrequest (request, response);}
It's all done here, the effect of the long passing success,
Using the servlet to upload file functions