Posted on 2006-12-24 11:30
兵临城下 阅读(1844)
评论(2) 编辑 收藏 所属分类:
Java EE
废话不多说,直接看程序:
Web端:
<form method = "post" id = "upload" action ="servlet/UploadServlet" enctype="multipart/form-data">
<input type = "file" id = "uploadFile" name = "uploadFile">
<input type="text" name ="text1">
<input type = "submit" value = "UPLOAD">
</form>
Servlet端:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map parameters = new HashMap();
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fu = new ServletFileUpload(factory);
fu.setSizeMax(4194304);
// 得到所有的文件,以及其它请求参数:
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
// 依次处理每一个文件,以及请求参数:
while(i.hasNext()) {
FileItem fi = (FileItem)i.next();
// 如果是文件项,则保存文件到上传目录
if (!fi.isFormField()) {
// 获得文件名,这个文件名包括路径:
String fileName = fi.getName();
long filesize = fi.getSize();
System.out.println("上传的文件名为!!!"+fileName + " size : " + filesize);
// 写入文件
fileName = fileName.substring(fileName.lastIndexOf("\\"));
String conPath = getServletContext().getRealPath("");
fi.write(new File(conPath + "//uploadFolder//" +fileName));
}
else { //如果是请求参数,则保存到HashMap中
String name = fi.getFieldName();
String value = fi.getString();
parameters.put(name, value);
System.out.println(parameters);
}
}
}
catch(Exception ex) {
System.out.println("上传文件时出错!!!");
ex.printStackTrace();
}
}
外加导入两个包:org.apache.commons.fileupload、org.apache.commons.io