今日实现了商家添加商品实现照片上传的功能,上传的照片将会保存在Web工程WebRoot中的images中。
主要通过form表单,将<input>标签的type设为file实现,注意form的方法必须为post且要设置enctype="multipart/form-data".
在servlet可以向读取文件流一样读取用户提交的文件。
servlet代码:
resp.setCharacterEncoding("utf-8"); try { DiskFileItemFactory fileitem=new DiskFileItemFactory(); ServletFileUpload servletfile=new ServletFileUpload(fileitem); List<FileItem> list; list=servletfile.parseRequest(req); for(FileItem fileItem:list) { InputStream inputStream =fileItem.getInputStream(); OutputStream outputStream=new FileOutputStream("C://Users//lenovo//Workspaces//MyEclipse 10//BuyIII//WebRoot//images//"+fileItem.getName()); int temp=0; while((temp=inputStream.read())!=-1) { outputStream.write(temp); } outputStream.close(); inputStream.close(); } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpSession session=req.getSession(); session.setAttribute("message","图片提交成功!"); req.getRequestDispatcher("additems.jsp").forward(req, resp);