Uploading files using JSP/Servlet is becoming a common task. The following is a simple routine that uses a free jspsmart component. You can download it at the JSPSMART site.
1. Html File
<Html>
<Body>
<Script LANGUAGE = "javascript" SRC = "JSFunction. js">
</Script>
<Script language = "JavaScript">
<! --
Function checkForm (){
If (document. uploadform. adsImage. value = ""){
Alert ("You must choose what image file to upload! ");
Return false;
}
Document. uploadform. submit ();
}
Function cancelUpload (){
Window. close ();
Window. opener. focus ();
}
// -->
</Script>
<Form name = "uploadform" method = "post"
Action = "uploadImage. jsp" ENCTYPE = "multipart/form-data"
Target = _ self>
<Center>
<Table border = "1" width = "65%">
<Tr>
<Td colspan = 2 nowrap align = center> ad Image Upload </td>
</Tr>
<Tr>
<Td width = "15%" nowrap> advertisement image: </td>
<Td width = "50%" nowrap> <input type = "file"
Name = "adsImage" size = "20"> </td>
</Tr>
<Tr>
<Td align = "center" colspan = 2>
<Input type = "button" value = "upload" onclick = "return
CheckForm (); ">
<Input type = "button" value = "Cancel" onclick = "return
CancelUpload (); ">
</Td>
</Tr>
</Form>
</Table>
<! --
<A href = "Javascript: window. close ();"> close this window </a>
-->
<Script language = "JavaScript">
<! --
This. focus ();
// -->
</Script>
</Body>
2. JSP File
<% @ Page language = "java" import = "com. jspsmart. upload .*,
Java. SQL. *, java. util. * "%>
<% -- Use SmartUpload bean -- %>
<Jsp: useBean id = "mySmartUpload" scope = "page"
Class = "com. jspsmart. upload. SmartUpload"/>
<%
// Initialization
MySmartUpload. init (config );
MySmartUpload. service (request, response );
// Set Restriction
MySmartUpload. setAllowedFilesList ("gif, bmp, jpeg, jpg ");
MySmartUpload. setTotalMaxFileSize (51200 );
// Upload
Try {
MySmartUpload. upload ();
}
Catch (Exception e ){
Out. println ("<font color = red> Upload File Fail! </Font>
<A href =
"JavaScript: window. history. back ();"> back </a> <br> ");
Out. println ("<UI> Notes: </UI> ");
Out. println ("<UL> You must set correct File
Name. </UL> ");
Out. println ("<UL> You file size must be less
50 K. </UL> ");
Out. println ("<UL> You can only upload. Gif. jpeg. jpg and
. Bmp files. </UL> ");
Return;
}
// Save file to disk
MySmartUpload. getFiles (). getFile (0). saveAs ("/" +
"FileName ");
%>
3. Servlet File (you can do it yourself)