List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory
public DiskFileItemFactory()
From source file:mercury.DigitalMediaController.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); try {// w w w. ja v a 2 s. com List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { Integer serial = (new DigitalMediaDAO()).uploadToDigitalMedia(item); String filename = item.getName(); if (filename.lastIndexOf('\\') != -1) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') != -1) { filename = filename.substring(filename.lastIndexOf('/') + 1); } String id = serial + ":" + filename; String encodedId = new String(new Base64().encode(id.getBytes())); encodedId = encodedId.replaceAll("\\\\", "_"); if (serial != null && serial != 0) { response.getWriter().write("{success: true, id: \"" + encodedId + "\"}"); return; } } } } catch (FileUploadException e) { e.printStackTrace(); } response.getWriter().write("{success: false}"); } else { String decodedId = null; DigitalMediaDTO dto = null; try { String id = request.getParameter("id"); id = id.replaceAll("_", "\\\\"); decodedId = new String(new Base64().decode(id.getBytes())); String[] splitId = decodedId.split(":"); if (splitId.length == 2 && splitId[0].matches("^\\d+$")) { dto = (new DigitalMediaDAO()).getDigitalMedia(Integer.valueOf(splitId[0]), splitId[1]); } } catch (Exception e) { // dto should be null here } InputStream in = null; byte[] bytearray = null; int length = 0; String defaultFile = request.getParameter("default"); response.reset(); try { if (dto != null && dto.getIn() != null) { response.setContentType(dto.getMimeType()); response.setHeader("Content-Disposition", "filename=" + dto.getFileName()); length = dto.getLength(); in = dto.getIn(); } if (in == null && StringUtils.isNotBlank(defaultFile)) { String path = getServletContext().getRealPath("/"); File file = new File(path + defaultFile); length = (int) file.length(); in = new FileInputStream(file); } if (in != null) { bytearray = new byte[length]; int index = 0; OutputStream os = response.getOutputStream(); while ((index = in.read(bytearray)) != -1) { os.write(bytearray, 0, index); } in.close(); } else { response.getWriter().write("{success: false}"); } } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{success: false}"); } response.flushBuffer(); } }
From source file:hd.controller.AddImageToIdeaBookServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//w w w . ja v a2 s. c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { //to do } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString("UTF-8")); } else if (!item.isFormField()) { try { long time = System.currentTimeMillis(); String itemName = item.getName(); fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName; File savedFile = new File(RealPath); item.write(savedFile); String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName; // savedFile = new File(localPath); // item.write(savedFile); } catch (Exception e) { e.printStackTrace(); } } } String ideaBookIdTemp = (String) params.get("txtIdeabookId"); int ideaBookId = Integer.parseInt(ideaBookIdTemp); IdeaBookDAO ideabookDao = new IdeaBookDAO(); String tilte = (String) params.get("newGalleryName"); String description = (String) params.get("GalleryDescription"); String url = "images/" + fileName; IdeaBookPhotoDAO photoDAO = new IdeaBookPhotoDAO(); IdeaBookPhoto ideaBookPhoto = photoDAO.insertIdeaBookPhoto(tilte, description, url, ideaBookId); HDSystem system = new HDSystem(); system.setNotificationIdeaBook(request); response.sendRedirect("MyIdeaBookDetailServlet?txtIdeabookId=" + ideaBookId); } } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
From source file:game.com.HandleUploadGameNesServlet.java
private void handle(HttpServletRequest request, AjaxResponseEntity responseObject) throws Exception { boolean isMultipart; String filePath;/*w w w . ja v a 2s . c o m*/ int maxFileSize = 4 * 1024 * 1024; int maxMemSize = 4 * 1024 * 1024; File file; DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("/tmp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); Map<String, List<FileItem>> postData = upload.parseParameterMap(request); String id = postData.get("id").get(0).getString(); if (StringUtils.isBlank(id)) { logger.info("id= " + id); } try { // Parse the request to get file items. List<FileItem> fileItems = postData.get("nes"); // Process the uploaded file items for (FileItem fi : fileItems) { if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file file = new File(AppConfig.OPENSHIFT_DATA_DIR + "/nes/" + id + ".zip"); fi.write(file); responseObject.data = getNesFileUrl(id); responseObject.returnCode = 1; responseObject.returnMessage = "success"; break; } else { logger.info("isFormField " + fi.getFieldName()); } } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } }
From source file:business.controllers.UploadImageController.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { PrintWriter writer = response.getWriter(); writer.println("Request does not contain upload data"); writer.flush();// ww w .j av a2 s. c om return; } String oauthCode = ""; // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE); upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE); List formItems = new ArrayList(); try { // parses the request's content to extract file data formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (item.getFieldName().equals("oauthcode")) { oauthCode = item.getString(); } } } catch (FileUploadException ex) { logger.error("Write image:" + ex); } //checkLogin BusinessChatHandler handler = new BusinessChatHandler(); try { if (handler.isLogin(oauthCode)) { uploadImage(request, response, formItems); } } catch (TException ex) { java.util.logging.Logger.getLogger(UploadImageController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:controller.Upload.java
/** * Servlet implementation class UploadServlet *///from w w w.ja va 2s . c o m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { return; } // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Sets the size threshold beyond which files are written directly to // disk. factory.setSizeThreshold(MAX_MEMORY_SIZE); // Sets the directory used to temporarily store files that are larger // than the configured size threshold. We use temporary directory for // java factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // constructs the folder where uploaded file will be stored String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY; // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MAX_REQUEST_SIZE); String fileName = "", newname = ""; try { // Parse the request List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { // fileName = (String)session.getId() + new File(item.getName()).getName(); // String filePath = uploadFolder + File.separator + fileName; fileName = new File(item.getName()).getName(); newname = (String) session.getId() + fileName.substring(fileName.lastIndexOf(".")); String filePath = uploadFolder + File.separator + newname; File uploadedFile = new File(filePath); System.out.println(filePath); // saves the file to upload directory item.write(uploadedFile); } } userDao ud = new userDao(); ud.changeuserpic((int) session.getAttribute("userID"), newname); // displays done.jsp page after upload finished getServletContext().getRequestDispatcher("/done.jsp").forward(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:com.ts.control.UploadFile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String campo1 = ""; String campo2 = ""; String campo3 = ""; String campo4 = ""; String campo5 = ""; String campo6 = ""; String campo7 = ""; int c = 1;/*from w ww. ja v a2 s . com*/ try { boolean ismultipart = ServletFileUpload.isMultipartContent(request); if (!ismultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { } Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { } else { String itemname = item.getName(); if ((itemname == null || itemname.equals(""))) { continue; } String filename = FilenameUtils.getName(itemname); System.out.println("ruta---------------" + saveFile + filename); File f = checkExist(filename); item.write(f); //////// List cellDataList = new ArrayList(); try { FileInputStream fileInputStream = new FileInputStream(f); XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream); XSSFSheet hssfSheet = workBook.getSheetAt(0); Iterator rowIterator = hssfSheet.rowIterator(); while (rowIterator.hasNext()) { XSSFRow hssfRow = (XSSFRow) rowIterator.next(); Iterator iterator = hssfRow.cellIterator(); List cellTempList = new ArrayList(); while (iterator.hasNext()) { XSSFCell hssfCell = (XSSFCell) iterator.next(); cellTempList.add(hssfCell); } cellDataList.add(cellTempList); } } catch (Exception e) { e.printStackTrace(); } out.println("<table border='3' class='table table-bordered table-striped table-hover'>"); for (int i = 1; i < cellDataList.size(); i++) { List cellTempList = (List) cellDataList.get(i); out.println("<tr>"); for (int j = 0; j < cellTempList.size(); j++) { XSSFCell hssfCell = (XSSFCell) cellTempList.get(j); String dato = hssfCell.toString(); out.print("<td>" + dato + "</td>"); switch (c) { case 1: campo1 = dato; c++; break; case 2: campo2 = dato; c++; break; case 3: campo3 = dato; c++; break; case 4: campo4 = dato; c++; break; case 5: campo5 = dato; c++; break; case 6: campo6 = dato; c++; break; case 7: campo7 = dato; c = 1; break; } } //model.Consulta.addRegistros(campo1,campo2,campo3,campo4,campo5,campo6,campo7); } out.println("</table><br>"); ///////// } } } } catch (Exception e) { } finally { out.close(); } }
From source file:ned.bcvs.admin.fileupload.CandidateFileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return;//from ww w . j a va2 s . c o m } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File( "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } //calling the ejb method to save voter.csv file to data base out.println(upbean.fileDbUploader(filePath + fileName, "candidate")); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:controller.uploadPergunta7.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww . j a v a2s . c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String idLocal = (String) request.getParameter("idLocal"); String expressaoModeloVolumePadrao = (String) request.getParameter("expressaoModeloVolumePadrao"); String equacaoAjustada = (String) request.getParameter("equacaoAjustada"); String idEquacaoAjustada = (String) request.getParameter("idEquacaoAjustada"); String name = ""; //process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); // item.write( new File(UPLOAD_DIRECTORY + File.separator + name)); item.write(new File(AbsolutePath + File.separator + name)); } } //File uploaded successfully request.setAttribute("message", "File Uploaded Successfully"); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } expressaoModeloVolumePadrao = expressaoModeloVolumePadrao.replace("+", "%2B"); equacaoAjustada = equacaoAjustada.replace("+", "%2B"); RequestDispatcher view = getServletContext().getRequestDispatcher("/novoLocalPergunta7?id=" + idLocal + "&nomeArquivo=" + name + "&expressaoModeloVolumePadrao=" + expressaoModeloVolumePadrao + "&equacaoAjustada=" + equacaoAjustada + "&idEquacaoAjustada=" + idEquacaoAjustada); view.forward(request, response); // request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response); // request.getRequestDispatcher("/novoLocalPergunta4?id="+idLocal+"&nomeArquivo="+name).forward(request, response); }
From source file:com.fjn.helper.common.io.file.upload.FileUploadHelper.java
/** * ?request?fireDir?request.setAttribute(fieldName, value)? * * @param request //from w ww .j ava 2 s .c om * @param fileDir * @param maxSize ? * @param isFileNameBaseTime ???? * @param encoding */ public static FileUploadRequestParamterContext upload(HttpServletRequest request, String fileDir, int maxSize, boolean isFileNameBaseTime, String encoding) { // ? if (!isFileUploadRequest(request)) return null; DiskFileItemFactory factory = new DiskFileItemFactory(); // dir?? File dir = new File(fileDir); if (!dir.exists()) { if (dir.mkdirs()) { throw new FileDirFaultException(dir); } ; } if (maxSize > 0) { factory.setSizeThreshold(maxSize); } factory.setRepository(dir); // ? ServletFileUpload fileUploader = new ServletFileUpload(factory); fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding); String realEncoding = fileUploader.getHeaderEncoding(); List<FileItem> items = null; try { items = fileUploader.parseRequest(request); } catch (FileUploadException e1) { e1.printStackTrace(); } if (items == null) return null; FileUploadRequestParamterContext context = new FileUploadRequestParamterContext(); Map<String, List<File>> fileMap = context.getFileMap(); Map<String, List<String>> fieldMap = context.getFormFieldMap(); FileItem fileItem = null; Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { fileItem = iter.next(); String fieldName = fileItem.getFieldName(); if (fileItem.isFormField()) { List<String> values = fieldMap.get(fieldName); if (values == null) { values = new ArrayList<String>(); fieldMap.put(fieldName, values); } String value = null; try { value = fileItem.getString(realEncoding); } catch (UnsupportedEncodingException e) { value = ""; e.printStackTrace(); } values.add(value); log.info("param:\t" + fieldName + "=" + value); } else { List<File> files = fileMap.get(fieldName); if (files == null) { files = new ArrayList<File>(); fileMap.put(fieldName, files); } String clientFileName = fileItem.getName();// ??? if (StringUtil.isNull(clientFileName)) { // continue; } String realFileName = FileUtil.getRealFileName(clientFileName); String newFileName = null; if (isFileNameBaseTime) { newFileName = new FileNameBuilder().build(realFileName); } else { newFileName = realFileName; } File tempfile = new File(dir, newFileName); try { fileItem.write(tempfile); log.info("???\t" + newFileName); files.add(tempfile); } catch (Exception e) { continue; } } } return null; }
From source file:de.knowwe.revisions.upload.UploadRevisionZip.java
@SuppressWarnings("unchecked") @Override// w w w .ja va2s . co m public void execute(UserActionContext context) throws IOException { HashMap<String, String> pages = new HashMap<>(); List<FileItem> items = null; String zipname = null; try { items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(context.getRequest()); } catch (FileUploadException e) { throw new IOException("error during processing upload", e); } for (FileItem item : items) { zipname = item.getName(); InputStream filecontent = item.getInputStream(); ZipInputStream zin = new ZipInputStream(filecontent); ZipEntry ze; while ((ze = zin.getNextEntry()) != null) { String name = ze.getName(); if (!name.contains("/")) { // this is an article String title = Strings.decodeURL(name); title = title.substring(0, title.length() - 4); String content = IOUtils.toString(zin, "UTF-8"); zin.closeEntry(); pages.put(title, content); } else { // TODO: what to do here? // this is an attachment // String[] splittedName = name.split("/"); // String title = Strings.decodeURL(splittedName[0]); // String filename = Strings.decodeURL(splittedName[1]); // // System.out.println("Attachment: " + name); // String content = IOUtils.toString(zin, "UTF-8"); // Environment.getInstance().getWikiConnector().storeAttachment(title, // filename, // context.getUserName(), zin); zin.closeEntry(); } } zin.close(); filecontent.close(); } if (zipname != null) { UploadedRevision rev = new UploadedRevision(context.getWeb(), pages, zipname); RevisionManager.getRM(context).setUploadedRevision(rev); } context.sendRedirect("../Wiki.jsp?page=" + context.getTitle()); }