First to introduce two jar packages, respectively
Commons-fileupload-1.3.1.jar
Commons-io-2.4.jar
index.jsp
<form action= "<%=path%>/test.jsp" method= "post" enctype= "Multipart/form-data" > <p> filename:< Input type= "text" name= "username" ></p> <p> Select Picture: <input type= "file" Name= "Nfile" ></p> <p ><input type= "Submit" value= "Submission" ></p> </form>
test.jsp
<%request.setcharacterencoding ("Utf-8"); BooleanFlag =servletfileupload.ismultipartcontent (request);if(flag) {Diskfileitemfactory Factory=Newdiskfileitemfactory (); Servletfileupload Upload=Newservletfileupload (Factory); List<FileItem> filelist =upload.parserequest (Request); Iterator<FileItem> Myitor =Filelist.iterator (); while(Myitor.hasnext ()) {Fileitem Item=Myitor.next (); if(item!=NULL){ if(Item.isformfield ()) {//proves that the normal form field returns the Name property value of a form fieldString name=Item.getfieldname (); if(Name.equals ("username") {out.print (item.getstring ("Utf-8")); } }Else{String filename=Item.getname (); String Path= "web-inf/upload/";//relative Path//It 's about converting the relative path into absolute path .String Absolutepath = This. Getservletcontext (). Getrealpath (path); File File=NewFile (filename); File UploadFile=NewFile (Absolutepath,file.getname ()); Item.write (UploadFile); Out.print ("Upload success!" "+filename); } } }}%>
Complete!
Implementing file Uploads