Java code// 创建工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置文件上传大小(单位KB)
upload.setSizeMax(-1);
try {
List items = upload.parseRequest(request);
Iterator it = items.iterator();
// 循环取出表单中元素
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
// 如果是FormField,则获取文件的名称并上传,否则打印表单信息
if (item.isFormField()) { // 不是文件域
String postName = item.getFieldName(); // 参数名
if("username".equals(postName)){
System.out.println("用户名是:"+item.getString()); // 参数值
}else if("userid".equals(postName)){
System.out.println("用户id是:"+item.getString());
}
} else { // 当是文件域的时候,执行上传写入硬盘操作
File temp = new File(item.getName());
System.out.println("文件名为:"+item.getName());
String path = request.getSession().getServletContext().getRealPath("/upload/");
File file = new File(path,temp.getName());
item.write(file);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}