1: First Initializes a form on the index.jsp interface.
<body> <form enctype= "Multipart/form-data" action= "<%=path%>/1.jsp" method= "POST" > Name: <input type= "text" name= "username"/> Select File: <input type= "file" name= "MyFile"/> <input Type= "Submit" value= "Submission"/> </form></body>
Enctype= multi-part form data, and if Enctype= "Multipart/form-data" is more in the properties of the form form, you cannot use the Request.getparameter (Name property)
2: Create a 1.jsp in the root directory of Web-root to achieve file upload function!
<% @page import= "Java.io.File"%><% @page import= "Org.apache.commons.fileupload.FileItem"%><% @page Import= "Org.apache.commons.fileupload.disk.DiskFileItemFactory"%><% @page import= " Org.apache.commons.fileupload.servlet.ServletFileUpload "%><%@ page language=" java "import=" java.util.* " pageencoding= "UTF-8"%><%//Decision Request type Request.setcharacterencoding ("Utf-8"); Boolean flag= servletfileupload.ismultipartcontent (request); if (flag) {diskfileitemfactory factory=new diskfileitemfactory (); Find a parser to parse each item in the request Servletfileupload Upload=new servletfileupload (Factory);//Parser Creation list<fileitem> List=upload.parserequest (request);//Use parser to parse the requested data iterator<fileitem> myitor= list.iterator ();//automatic Iteration function while (Myitor.hasnext ()) {Fileitem item=myitor.next (); if (item!=null) {//determines the data type encapsulated by the Fileitem object, the file form or the normal form field if (ITEM.isformfield ())//normal form {String name= item.getfieldname ();//Gets the Name property of the form if (Name.equals ("username")) {Out.print (item.getstring ("Utf-8")); }} else {String name=item.getname ();//Get file name Out.print (name); String path= "/web-inf/upload/";//relative path name String path2=this.getservletcontext (). Getrealpath (path);//Pass relative path Name to obtain the absolute path name Out.print (path2); File File=new file (name); File Uploadpath=new file (Path2,file.getname ()); Item.write (Uploadpath);//write file Out.print to the path ("Upload succeeded"); }}}}%>
File Upload function