There are many available class libraries for file uploading in JSP, such as the famous jspsmart company smartupload and struts. Here I will talk about cos. It is from o'reilly, and o'reilly's book is very 8 wrong. This uploaded component is also doing great, and most importantly, it is open source.
1. download the latest cos package (http://www.servlets.com/cos/index.html) and add it to your classpath
2. Compile a JSP file to be uploaded. For convenience, I will use a simple HTM file. on this page, we allow users to upload three files at a time.
/// // Upload.htm ////////////////// ////////////////////
[Pre] <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"
Http://www.w3.org/TR/html4/loose.dtd>
<HTML>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Title> untitled document </title>
</Head>
<Body>
<! -- The value of enctype is very important. Upload. jsp is the JSP for processing uploads -->
<Form name = "form1" method = "Post" enctype = "multipart/form-Data" Action = "Upload. jsp">
<P>
<Input name = "file1" type = "file">
</P>
<P>
<Input name = "file2" type = "file">
</P>
<P> <input name = "file3" type = "file">
</P>
<P>
<Input type = "Submit" name = "Submit" value = "Upload">
</P>
</Form>
</Body>
</Html> [/PRE]
3. Create a directory c:/upload under C:/to store uploaded files.
4. Write a JSP or servlet for upload. I use Upload. jsp here, so you don't need to configure web. xml.
/// // Upload. JSP ////////////////////////////////////////
<% @ PageImport= "Java. Io. *" %>
<% @ PageImport= "Com. oreilly. servlet. multipartrequest" %>
<% @ PageImport= "Com. oreilly. servlet. multipart. coverfilerenamepolicy" %>
<% @ Page contenttype = "text/html; charset = gb2312" %>
<%
// After the file is uploaded, it is stored in C: // upload
String savedirectory = "C: // upload ";
// Each file can contain a maximum of 5 MB and a maximum of 3 files, so...
IntMaxpostsize = 3*5*1024*1024;
// The response is encoded as "gb2312", and the default file name conflict resolution policy is used for uploading.
Multipartrequest multi =
NewMultipartrequest (request, savedirectory, maxpostsize,
"Gb2312 ");
// Output Feedback
Enumeration files = multi. getfilenames ();
While(Files. hasmoreelements ()){
System. Err. println ("CCC ");
String name = (string) files. nextelement ();
File F = multi. GetFile (name );
If(F! = NULL ){
String filename = multi. getfilesystemname (name );
String lastfilename = savedirectory + "//" + filename;
Out. println ("uploaded file:" + lastfilename );
Out. println ("<HR> ");
}
}
%>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
5. Finally, just release the two files to your server. You can just upload the file. In the future, you want to embed the function of sending attachments in your email system. It is good to use this function for uploading.