public MetadataUploadService() { File servletTmpDir; try { // Get the temporary directory used by the servlet servletTmpDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir"); } catch (Exception ex) { // Just use the default system temp dir (less secure) servletTmpDir = null; } // Create a disk file item factory for processing requests DiskFileItemFactory factory = new DiskFileItemFactory(); if (servletTmpDir != null) { // Use the temporary directory for the servlet for large files factory.setRepository(servletTmpDir); } // Create the file uploader using this factory metadataUpload = new ServletFileUpload(factory); }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String message = "File upload."; List<String> filenames = null; isMultipart = ServletFileUpload.isMultipartContent(request); HttpSession session = request.getSession(false); User loggedUser = null; if (session != null) loggedUser = (User) session.getAttribute("loggedUser"); if (loggedUser == null) { request.getRequestDispatcher("login.jsp").forward(request, response); } else { Book book = new Book(); if (isMultipart) { ServletContext context = this.getServletConfig().getServletContext(); DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. File repoPath = (File) context.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repoPath); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { List<FileItem> fileItems = upload.parseRequest(new ServletRequestContext(request)); filePath = request.getServletContext().getRealPath("/") + "picture/"; filenames = new ArrayList<String>(); for (FileItem fi : fileItems) { if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); if (fi.getName() != null && !fi.getName().equals("")) { String fileName = URLEncoder.encode(fi.getName(), "UTF-8"); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); file = new File(filePath + fileName); fi.write(file); book.setPictureURL("picture/" + fileName); } } else { String fieldName = fi.getFieldName(); String fieldValue = fi.getString(); if (fieldName.equals("title")) { if (fieldValue != null) { book.setTitle(fieldValue); ; } } if (fieldName.equals("authors")) book.setAuthors(fieldValue); if (fieldName.equals("publisher")) book.setPublisher(fieldValue); if (fieldName.equals("description")) if (fieldValue != null) { book.setDescription(fieldValue); } if (fieldName.equals("genre")) book.setGenre(fieldValue); if (fieldName.equals("numberInStock")) book.setNumberInStock(Integer.parseInt(fieldValue)); if (fieldName.equals("publicationYear")) book.setPublicationYear(Integer.parseInt(fieldValue)); if (fieldName.equals("price")) book.setPrice(Double.parseDouble(fieldValue)); } } } catch (Exception ex) { System.out.println(ex); } } BookDAO bookDao = new BookDAO(); bookDao.add(book); response.sendRedirect("LoginBookPreviewViewController"); } }
private void updateCover( HttpServletRequest request, HttpServletResponse response, final String method) throws FileUploadException, ServletException, IOException, IllegalAccessException, InvocationTargetException { List<String> types = Arrays.asList(".jpg", ".gif", ".png", ".jpeg"); // supported // type DiskFileItemFactory dfi = new DiskFileItemFactory(); // apache's // component dfi.setSizeThreshold(1024 * 1024); // 1M, and default is 10k, and // excessed will be saved in the // cache file String path = getServletContext().getRealPath("/WEB-INF/temp"); dfi.setRepository(new File(path)); // temporary cached file ServletFileUpload sf = new ServletFileUpload(dfi); sf.setHeaderEncoding("utf-8"); // sf.setFileSizeMax(1024*1024*5); //set single file's max size List<FileItem> lf = sf.parseRequest(new ServletRequestContext(request)); Map<String, String> map = new HashMap<String, String>(); List<String> idf = new LinkedList<String>(); FileItem fi = null; // for stream file String ids[]; for (FileItem item : lf) { if (item.isFormField()) { // ordinary input String name = item.getFieldName(); String value = item.getString("utf-8"); map.put(name, value); if ("category".equals(name)) { idf.add(value); } System.out.println(name + " " + value); } else { // stream String name = item.getName(); if (name == null || "".equals(name)) { continue; } String ext = name.substring(name.lastIndexOf(".")); System.out.println(ext); if (!types.contains(ext.toLowerCase())) { request.setAttribute("message", "sorryia.. i don't support type " + ext); return; } fi = item; } } Book book = new Book(); ConvertUtils.register(new DateLocaleConverter(), Date.class); BeanUtils.populate(book, map); BookDaoImpl bdi = new BookDaoImpl(); ids = new String[idf.size()]; idf.toArray(ids); int id; if (method.equals(BOOK_ADD)) { id = bdi.add(book, ids); request.setAttribute("message", "add book successfully..."); } else { id = Integer.parseInt(map.get("id")); book.setId(id); bdi.update(book); bdi.updateCategory(id, ids); request.setAttribute("message", "update book successfully..."); } if (fi != null) { // upload file InputStream is = fi.getInputStream(); String Spath = getServletContext().getRealPath("/img/bookcover/"); System.out.println(Spath); FileOutputStream fos = new FileOutputStream(new File(Spath + id + ".jpg")); byte[] b = new byte[1024]; int len = 0; while ((len = is.read(b)) > 0) { fos.write(b, 0, len); } fos.close(); is.close(); fi.delete(); // the temporary file would be deleted. } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String idx = request.getParameter("idx"); // 获得磁盘文件条目工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); // 获取文件需要上传到的路径 String rootPath = getServletContext().getRealPath("/upload"); // 如果没以下两行设置的话,上传大的 文件 会占用 很多内存, // 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同 /** 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的 然后再将其真正写到 对应目录的硬盘上 */ File uploadDir = new File(rootPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } factory.setRepository(uploadDir); // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室 factory.setSizeThreshold(1024 * 1024); boolean isUpload = ServletFileUpload.isMultipartContent(request); // 高水平的API文件上传处理 ServletFileUpload upload = new ServletFileUpload(factory); try { // 可以上传多个文件 List<FileItem> list = (List<FileItem>) upload.parseRequest(request); for (FileItem item : list) { // 获取表单的属性名字 String fileName = item.getName(); // 如果获取的 表单信息是普通的 文本 信息 if (item.isFormField()) { } // 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些 else { String md5Name = MD5Code.getInstance().getCode(fileName + System.currentTimeMillis()); String fiffux = fileName.substring(fileName.lastIndexOf(".")); // 真正写到磁盘上 // 它抛出的异常 用exception 捕捉 File f = new File(rootPath + File.separatorChar, md5Name + fiffux); if (!f.exists()) { f.createNewFile(); } item.write(f); // 第三方提供的 JSONObject result = new JSONObject(); JSONObject payload = new JSONObject(); responseJavaScript( out, "parent.uploadImageComplete('" + idx + "','" + (md5Name + fiffux) + "')"); out.close(); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }