<form name="UploadForm" enctype="multipart/form-data" method="post" action="upLoadImage.do"> <input type="file" name="File1" size="11" maxlength="20"/><input type="submit"value="上 传"/> </form> String path="images//product//"; String temp=this.getServlet().getServletContext().getRealPath("/")+"temp"; //临时目录 String loadpath=this.getServlet().getServletContext().getRealPath("/")+path; //上传文件存放目录 DiskFileUpload fu = new DiskFileUpload(); fu.setSizeMax(10*1024*1024); // 设置允许用户上传文件大小,单位:字节 fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:字节 fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 //开始读取上传信息 List fileItems = fu.parseRequest(request); System.out.println(fileItems.size());//输出上传文件信息 Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件 while (iter.hasNext()) { FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息 if (!item.isFormField()) { String name = item.getName();//获取上传文件名,包括路径 name=name.substring(name.lastIndexOf("//")+1);//从全路径中提取文件名 long size = item.getSize(); if((name==null||name.equals("")) && size==0){ request.setAttribute("uploadmessage","上传图片失败!"); return mapping.findForward("product"); } File fNew= new File(loadpath, name); item.write(fNew); request.setAttribute("uploadmessage","上传图片成功!"); HttpSession session=request.getSession(); session.setAttribute("path",(path+fNew.getName()).replace("//","/")); System.out.println((path+fNew.getName()).replace("//","/")); } }