采用了tomcat發(fā)布,調用了jarkarta的一個common-fileup組件,
著先配置好classpath,加上servlet.jar和commons-fileupload-1.0.jar,
然后把commons-fileupload-1.0.jar放到root下的web-inf/lib/下
編寫up.java并編繹,放到web-inf/classes目錄下
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class up extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GB2312";
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 設置允許用戶上傳文件大小,單位:字節(jié),這里設為2m
fu.setSizeMax(2*1024*1024);
// 設置最多只允許在內(nèi)存中存儲的數(shù)據(jù),單位:字節(jié)
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數(shù)據(jù)存放在硬盤的目錄
fu.setRepositoryPath("c:\\windows\\temp");
//開始讀取上傳信息
List fileItems = fu.parseRequest(request);
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
//正則匹配,過濾路徑取文件名
String regExp=".+\\\\(.+)$";
//過濾掉的文件類型
String[] errorType={".exe",".com",".cgi",".asp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表單信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;temp<errorType.length;temp++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type");
}
}
try{
//保存上傳的文件到指定的目錄
//在下文中上傳文件至數(shù)據(jù)庫時,將對這里改寫
item.write(new File("d:\\" + m.group(1)));
out.print(name+" "+size+"<br>");
}
catch(Exception e){
out.println(e);
}
}
else
{
throw new IOException("fail to upload");
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
}
}
然后布署好web.xml,在其中加入
<servlet>
<servlet-name>up</servlet-name>
<servlet-class>up</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>up</servlet-name>
<url-pattern>/fileup</url-pattern>
</servlet-mapping>
好了現(xiàn)在再編寫一個htm測試一下就ok了,注意url-pattern里面的路徑必須跟表格中action的屬性一樣.
<html>
<h1>文件上傳演示</h1>
<form name="uploadform" method="POST" action="/fileup" ENCTYPE="multipart/form-data">
<table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF">
<tr><td width="100%" colspan="2">
文件1:<input name="x" size="40" type="file">
</td></tr>
<tr><td width="100%" colspan="2">
文件2:<input name="y" size="40" type="file">
</td></tr>
<tr><td width="100%" colspan="2">
文件3:<input name="z" size="40" type="file">
</td></tr>
</table>
<br/><br/>
<table>
<tr><td align="center"><input name="upload" type="submit" value="開始上傳"/></td></tr>
</table>
</form>
</html>
posted on 2005-10-27 12:43
rkind 閱讀(261)
評論(0) 編輯 收藏 所屬分類:
JSP&Servlet