<form action="../FileUpload" method="post" enctype="multipart/form-data" name="form1">
<input type="file" name="file"> 
<input type="submit"name="Submit" value="upload">
</form>try {
List fileItems = upload.parseRequest(req);
// 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", ".asp" };
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName(); //此处应该得到是一个文件的名字(绝对路径),却只能得到一个文件名称,没有路径。(这是我问题的所在)
name = "e:\\" + name; //不能得到路径,自己手动加的一个路径,才顺利上传。(为了试验能上传文件,我自己加的"e:\\")
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("d:\\" + m.group(1)));
out.print(name + "&nbsp;&nbsp;" + 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);
}