上代码:
@WebServlet(urlPatterns = "/insert")
public class AddContact extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
SmartUpload smartUpload = new SmartUpload();
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024, true);
smartUpload.initialize(pageContext);
smartUpload.setCharset("utf-8");
smartUpload.upload();
String sex = smartUpload.getRequest().getParameter("sex");
String stuid = smartUpload.getRequest().getParameter("stuId");
int classId = Integer.parseInt(smartUpload.getRequest().getParameter("classId"));
String mobile = smartUpload.getRequest().getParameter("phone");
String email = smartUpload.getRequest().getParameter("email");
String qq = smartUpload.getRequest().getParameter("qq");
String name = smartUpload.getRequest().getParameter("name");
File file = smartUpload.getFiles().getFile(0);
String fileName = file.getFileName();
System.out.println(fileName);
fileName=name+".jpg";
System.out.println(fileName);
String path = "/saveFile/" + fileName;
file.saveAs(path, File.SAVEAS_VIRTUAL);
resp.sendRedirect("index.jsp");
}catch (SQLException e){
e.printStackTrace();
HttpSession session = req.getSession();
session.setAttribute("error","该学号已添加到通讯录");
System.out.println("出错了");
resp.sendRedirect("register.jsp");
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
}
注意事项
- form表单必须添加enctype=“multipart/form-data”,而且还得是post提交才行
- 当表单添加了enctype="multipart/form-data"时获取表单提交的数据就不能用req.getParameter()来获取,必须要用smartUpload.getRequest().getParameter();