<!-- -->
public class FileUpload extends HttpServlet {
public void destroy() {
/* config = null;*/
super.destroy();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
System.out.println(request.getContentLength());
System.out.println(request.getContentType());
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(4096);
factory.setRepository(new File("f:\\temp\\"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1000000);
try {
List fileItems = upload.parseRequest(request);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator iter = fileItems.iterator();
String regExp = ".+\\\\(.+)$";
String[] errorType = { ".exe", ".com", ".cgi", ".jsp" };
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 {
item.write(new File( "f:\\"+ 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);
}
}
}