1. First download the Cos.jar package and add it to the Eclipse Web project Lib
2. Create a form on the JSP page as follows:
<form action= "FileUpload" method= "post" enctype= "Multipart/form-data" >
<table border= "0" >
<tr> <td valign= "Top" >
<strong>please Choose your document:</strong>
<br>
</td>
<td>
<input type= "File" name= "File1" >
<br>
</td>
</tr>
<tr>
<td>
<input type= "Submit" value= "Upload File" >
</td>
</tr> </table>
</form>
The red part must be set otherwise the upload is unsuccessful
3. Create a servlet as follows:
public class FileUpload extends HttpServlet {
Private String Webtemppath;
public void init () {
Webtemppath = Getservletcontext (). Getrealpath ("/") + "upload";
}
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, Java.io.IOException {
Response.setcontenttype ("Text/plain");
Request.setcharacterencoding ("GBK");
Response.setcharacterencoding ("GBK");
File limit size of 5 MB
Multipartrequest MPR = new Multipartrequest (Request, Webtemppath, 120*1024*1024, "gb2312", New Defaultfilerenamepolicy ( ));
System.out.println ("The file length is::" +mpr.getfile (Webtemppath). Length ());
Enumeration params = Mpr.getfilenames ();
Mpr.getparameter ("name");
Response.setcontenttype ("text/html");
PrintWriter out = Response.getwriter ();
Out.println ("Out.println ("Out.println ("<title>servlet upload</title>");
Out.println ("Out.println ("<body>");
for (int i = 1; params.hasmoreelements (); i++) {
String Src=new string (Mpr.getfilesystemname (String) params.nextelement ());
System.out.println (Mpr.getfilesystemname (String) params.nextelement ()). Length ());
File File=new file (webtemppath+ "/" +src);
System.out.println ("The file length is::" +file.length ());
SYSTEM.OUT.PRINTLN (SRC);
Out.println ("The name of uploaded file" + i + "is:" + src+ "<br><br>");
}
Out.println ("</body>");
Out.println ("
}
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, Java.io.IOException {
DoPost (request, response);
}
}
4. Add the servlet mappings below the Web. xml file
<servlet>
<description>this is the description of my EE component</description>
<display-name>this is the display name of my EE component</display-name>
<servlet-name>FileUpload</servlet-name>
<servlet-class>com.icss.servlet.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUpload</servlet-name>
<url-pattern>/FileUpload</url-pattern>
</servlet-mapping>