今天完成了一个上传文件的功能
在网页点击上传可以将文件上传到java文件下
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=UTF-8"); boolean isMultipart=ServletFileUpload.isMultipartContent(request); if(isMultipart) { FileItemFactory factory=new DiskFileItemFactory(); ServletFileUpload upload=new ServletFileUpload(factory); try { List<FileItem> items=upload.parseRequest(request); Iterator<FileItem> it = items.iterator(); while(it.hasNext()) { FileItem item = it.next(); String itemname = item.getFieldName(); int sno=-1; String sname=null; if(item.isFormField()) { if(itemname.equals("sno")) { sno=Integer.parseInt(item.getString("utf-8")); }else if(itemname.equals("sname")) { sname=item.getString("utf-8"); sname=item.getName(); }else { System.out.println("其他字段"); } }else { String filename=item.getName(); String path=request.getSession().getServletContext().getRealPath("download"); //String path="E:\upload"; //System.out.println(path); File file=new File(path,filename); item.write(file); request.setAttribute("news", filename+"上传成功,谢谢分享"); request.getRequestDispatcher("print.jsp").forward(request, response); System.out.println(filename+"上传成功!!!"); return; } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }