In the http://www.apache.org, download the commons-fileupload-1.2.1.jar package and add this package to the project. Below are some ways to record this Upload Component.
On the HTML test page, upload two files and fill in four parameters.
<form action="../FileServlet" enctype="multipart/form-data" method="post" >
<DT> Name: </DT> <DD> <input type = "text" name = "name" class = "file-input"/> DD> <DT> bank account: </DT> <DD> <input type = "text" name = "Account" class = "file-input"/> </DD> <DT> bank: </DT> <DD> <input type = "text" name = "bank" class = "file-input"/> <DD> <DT> ID card number: </DT> <DD> <input type = "text" name = "Number" class = "file-input"/> </DD> <DT> ID Card Photo: </DT> <DD> <input type = "file" name = "photo" class = "file-input"/> </DD> <DT> Bank Card Photo: </DT> <DD> <input type = "file" name = "card" class = "file-input"/> </DD>
</form>
When uploading a file, the entype of the form must be multipart/form-data. In this case, parameters cannot be obtained through the request. getparameter (); Method on the platform, and null values are returned. Therefore, the getparameter () method cannot be used here. The following describes some methods in commons-fileupload.
First, encapsulate each item in the Request Message entity into a separate diskfileitem (fileitem implementation) object. apache. commons. fileupload. org. apache. commons. fileupload. diskfileitemfactory. When the uploaded file is small, it can be directly stored in the memory, which is faster. When the file is large, the Temporary File Cache is used. The Code is as follows:
Fileitemfactory factory = new diskfileitemfactry ();
Servletfileupload upload = new servletfileupload (factory); // obtain the servletfileupload object upload
List <fileitem> listitem = upload. parserequest (request); // parse the request and encapsulate each project into a separate fileitem
// Traverse listitem
For (fileitem item: listitem ){
If (! Item. isformfield () {// indicates that this project is a file and uploaded to the server
String filename = item. getname (); // The complete path name of the file.
String fileuploadname = filename. substring (filename
. Lastindexof ("\") + 1); // obtain the file name, excluding the path
Item. Write (new file (path, fileuploadname); // write to disk, path is the file write path
} Else {// This project is a parameter that can be obtained
String filed = item. getfieldname (); // obtain this parameter name
If (filed. Equals ("bank") {// obtain the parameter value based on the judgment and assign it to the declared variable
Bank = item. getstring ();
}
If (filed. Equals ("Number ")){
Number = item. getstring ();
}
If (filed. Equals ("account ")){
Account = item. getstring ();
}
}
}
In this way, the file is uploaded and the page parameters are obtained.