List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository
public void setRepository(File repository)
From source file:org.silverpeas.mobile.server.servlets.FormServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//w w w . j a v a 2s. com String instanceId = null; String currentAction = null; String currentRole = null; String currentState = null; String processId = null; HashMap<String, Object> fields = new HashMap<String, Object>(); String charset = "UTF-8"; String tempDir = MediaHelper.getTemporaryUploadMediaPath(); // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(tempDir)); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // Parse the request @SuppressWarnings("unchecked") List<FileItem> items = null; items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("instanceId")) { instanceId = item.getString(charset); } else if (item.getFieldName().equals("currentAction")) { currentAction = item.getString(charset); } else if (item.getFieldName().equals("currentRole")) { currentRole = item.getString(charset); } else if (item.getFieldName().equals("currentState")) { currentState = item.getString(charset); } else if (item.getFieldName().equals("processId")) { processId = item.getString(charset); } else { fields.put(item.getFieldName(), item.getString(charset)); } } else { String fileName = item.getName(); File file = new File(tempDir + File.separator + fileName); item.write(file); fields.put(item.getFieldName(), file); } } processAction(request, response, fields, instanceId, currentAction, currentRole, currentState, processId); } catch (FileUploadBase.FileSizeLimitExceededException eu) { response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; } catch (Exception e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.silverpeas.mobile.server.servlets.MediaServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String componentId = ""; String albumId = ""; String tempDir = MediaHelper.getTemporaryUploadMediaPath(); // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(tempDir)); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // Parse the request @SuppressWarnings("unchecked") List<FileItem> items = null; try {//www . ja va 2 s . c om items = upload.parseRequest(request); } catch (FileUploadBase.FileSizeLimitExceededException eu) { response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; } catch (FileUploadException e) { e.printStackTrace(); } // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("componentId")) componentId = item.getString(); if (item.getFieldName().equals("albumId")) albumId = item.getString(); } else { String fileName = item.getName(); File file = new File(tempDir + File.separator + fileName); try { item.write(file); createMedia(request, response, fileName, getUserInSession(request).getId(), componentId, albumId, file, false, "", "", true); } catch (Exception e) { e.printStackTrace(); } } } }
From source file:org.structr.web.servlet.DeploymentServlet.java
@Override public void init() { try (final Tx tx = StructrApp.getInstance().tx()) { DiskFileItemFactory fileFactory = new DiskFileItemFactory(); fileFactory.setSizeThreshold(MEMORY_THRESHOLD); filesDir = new File(Settings.TmpPath.getValue()); // new File(Services.getInstance().getTmpPath()); if (!filesDir.exists()) { filesDir.mkdir();/*from w w w.j av a 2 s .c o m*/ } fileFactory.setRepository(filesDir); uploader = new ServletFileUpload(fileFactory); tx.success(); } catch (FrameworkException t) { logger.warn("", t); } }
From source file:org.structr.web.servlet.UploadServlet.java
@Override public void init() { try (final Tx tx = StructrApp.getInstance().tx()) { DiskFileItemFactory fileFactory = new DiskFileItemFactory(); fileFactory.setSizeThreshold(MEMORY_THRESHOLD); filesDir = new File(Services.getInstance().getConfigurationValue(Services.TMP_PATH)); // new File(Services.getInstance().getTmpPath()); if (!filesDir.exists()) { filesDir.mkdir();/*w ww . j av a 2 s. c o m*/ } fileFactory.setRepository(filesDir); uploader = new ServletFileUpload(fileFactory); tx.success(); } catch (FrameworkException t) { t.printStackTrace(); } }
From source file:org.talend.esb.job.console.DeployServlet.java
public void doIt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); // set the size threshold, above which content will be stored on disk fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1MB // set the temporary directory to store the uploaded files of size above threshold fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try {/* w w w. j av a2s. co m*/ // parse the request List items = uploadHandler.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { File file = new File(deployDir, item.getName()); item.write(file); Bundle bundle = bundleContext.installBundle("file://" + file.getAbsolutePath()); bundle.start(); } } } catch (Exception e) { response.sendRedirect("home.do?error=" + e.getMessage()); return; } response.sendRedirect("home.do"); }
From source file:org.topicquests.backside.servlet.apps.upload.UploadHandler.java
/** * Accept the upload instructions//from w ww.ja v a 2 s. c om * (non-Javadoc) * @see org.topicquests.backside.servlet.apps.BaseHandler#handlePost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.topicquests.ks.api.ITicket, net.minidev.json.JSONObject) */ public void handlePost(HttpServletRequest request, HttpServletResponse response, ITicket credentials, JSONObject jsonObject) throws ServletException, IOException { System.out.println("UPLOADPOSTING-4"); // System.out.println("CONTENTLENGTH "+request.getHeader("Content-length")); // System.out.println("CONTENTTYPE "+request.getContentType()); String verb = request.getParameter("verb"); //getParameter("verb"); //InputStream ins = request.getInputStream(); //System.out.println("AVAILABLE "+ins.available()); System.out.println("MULTI " + ServletFileUpload.isMultipartContent(request)); Map<String, String[]> m = request.getParameterMap(); System.out.println("PARAMMAP " + m); String user = credentials.getUserLocator(); System.out.println("FILEUPLOAD VERB " + verb + " " + user); environment.logDebug("UploadHandler.post " + verb + " " + user); String thePath = ""; //TODO calculate the directory path for this file ///////////////////////////// //TODO: thePath will be dependent on a verb retrieved from request ///////////////////////////// try { File repository = new File(thePath); String uploadPath = repository.getAbsolutePath() + "/"; DiskFileItemFactory dfiFactory = dfiFactory = new DiskFileItemFactory(); dfiFactory.setRepository(repository); ServletFileUpload servletFileUpload = new ServletFileUpload(dfiFactory); System.out.println("PARSING"); List<FileItem> items = servletFileUpload.parseRequest(request); System.out.println("FILEUPLOADING " + verb + " | " + items.size()); /* Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); String fileName = item.getName(); if (item.isFormField()) { //TODO processFormField(item); } else { //TODOprocessUploadedFile(item); File f = new File(uploadPath+fileName); item.write(f); } //TODO would be nice to have a socket and show progress } */ } catch (Exception e) { environment.logError(e.getMessage(), e); e.printStackTrace(); } //Todo SOME KIND OF RETURN RESPONSE }
From source file:org.wyona.yanel.servlet.communication.HttpRequest.java
/** * @param maxFileSize Maximum file size//from www .j a v a 2s. c o m */ public HttpRequest(HttpServletRequest request, long maxFileSize) throws ServletException { super(request); if (isMultipartRequest()) { try { DiskFileItemFactory factory = new DiskFileItemFactory(); // INFO: Set factory constraints int maxSize = 64000; // TODO: Make configurable factory.setSizeThreshold(maxSize); //log.info("Size threshold: " + factory.getSizeThreshold() + " bytes"); File repoDir = new File(System.getProperty("java.io.tmpdir")); factory.setRepository(repoDir); //log.info("Repository directory where temporary files will be created in order to handle files beyond the size threshold: " + factory.getRepository()); // INFO: Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); if (maxFileSize >= 0) { upload.setFileSizeMax(maxFileSize); log.warn("DEBUG: Maximum file size: " + upload.getFileSizeMax() + " bytes"); } else { log.warn("No maximum file size limit set, hence unlimited!"); } // INFO: Parse the request items = upload.parseRequest(request); } catch (Exception e) { log.error(e, e); if (e.getClass().getName().indexOf("FileSizeLimitExceededException") >= 0) { //if (e instanceof org.apache.commons.fileupload.FileUploadBase$FileSizeLimitExceededException) { setMultipartRequestException(e); // TODO: Set a yanel based exception in order to hide apache commons implementation } else { setMultipartRequestException(e); } log.warn("Create empty list of items in order to prevent NullPointer exceptions!"); items = new java.util.ArrayList(); // INFO: Create empty list, such that no NullPointer is being generated } } else { //log.debug("No multipart request '" + request.getServletPath() + "', hence do nothing."); } }
From source file:org.xchain.framework.servlet.MultipartFormDataServletRequest.java
private static DiskFileItemFactory createDiskFileItemFactory(int sizeThreshold, String repositoryPath) throws FileUploadException { DiskFileItemFactory factory = new DiskFileItemFactory(); // the location for saving data that is larger than getSizeThreshold() File repository = new File(repositoryPath); factory.setRepository(repository); // maximum size that will be stored in memory factory.setSizeThreshold(sizeThreshold); // Check to see if repository exists; if not, try to create it; if this fails, throw an exception. if (repository.exists()) { if (!repository.isDirectory()) { throw new FileUploadException("Cannot upload files because the specified temporary " + "directory is of type file. (" + repository.getAbsolutePath() + ")"); }//w ww. ja v a 2 s . c o m } else if (!repository.mkdir()) { throw new FileUploadException("Cannot upload files because the specified temporary " + " does not exist, and attempts to create it have failed. (" + repository.getAbsolutePath() + ")"); } return factory; }
From source file:pe.edu.upeu.application.web.controller.CDocumento.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException, Exception { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String dgp = request.getParameter("iddgp"); String idtr = request.getParameter("idtr"); String opc = request.getParameter("opc"); HttpSession sesion = request.getSession(true); String user = (String) sesion.getAttribute("IDUSER"); try {/*from ww w. j av a 2 s . c o m*/ if (opc != null) { if (opc.equals("Eliminar")) { String id_doc_adj = request.getParameter("id_doc"); d.Desactivar_doc(id_doc_adj); int s = d.List_Req_nacionalidad(idtr); int num_ad = d.List_Adventista(idtr); sesion.setAttribute("List_Hijos", d.List_Hijos(idtr)); sesion.setAttribute("List_doc_req_pla", d.List_doc_req_pla(dgp, idtr)); sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr)); response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad=" + num_ad + "&idtr=" + idtr + "&iddgp=" + dgp + "&pro=pr_dgp&a=e"); } if (opc.equals("Ver_Documento")) { sesion.setAttribute("List_doc_req_pla", d.List_doc_req_pla(dgp, idtr)); int i = d.List_Req_nacionalidad(idtr); int num_ad = d.List_Adventista(idtr); sesion.setAttribute("List_Hijos", d.List_Hijos(idtr)); sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr)); response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + i + "&num_ad=" + num_ad + "&idtr=" + idtr); } if (opc.equals("Reg_Pro_Dgp")) { sesion.setAttribute("List_doc_req_pla", d.List_doc_req_pla(dgp, idtr)); int i = d.List_Req_nacionalidad(idtr); int num_ad = d.List_Adventista(idtr); sesion.setAttribute("List_Hijos", d.List_Hijos(idtr)); sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr)); response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + i + "&num_ad=" + num_ad + "&pro=pr_dgp"); } if (("Listar_doc").equals(opc)) { int s = d.List_Req_nacionalidad(idtr); int num_ad = d.List_Adventista(idtr); int can_doc = d.count_documentos(dgp); sesion.setAttribute("List_Hijos", d.List_Hijos(idtr)); sesion.setAttribute("List_doc_req_pla", d.List_doc_req_pla(dgp, idtr)); sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr)); if (can_doc > 0) { response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad=" + num_ad + "&P2=TRUE&idtr=" + idtr + "&iddgp=" + dgp); } else { response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad=" + num_ad + "&idtr=" + idtr + "&iddgp=" + dgp + "&pro=pr_dgp"); } } } else { // String ubicacion = getServletConfig().getServletContext().getRealPath("/") + "Vista/Dgp/Documento/Archivo/"; String ubicacion = FactoryConnectionDB.url + "Archivo/"; DiskFileItemFactory f = new DiskFileItemFactory(); f.setSizeThreshold(1024); f.setRepository(new File(ubicacion)); ServletFileUpload upload = new ServletFileUpload(f); ServletRequestContext src = new ServletRequestContext(request); List<FileItem> p = upload.parseRequest(src); int num_filas = 0; String iddgp = null; String pr = null; String id_ctr = null; String id_h = null; List<String> list_files = new ArrayList<String>(); Iterator itera = p.iterator(); while (itera.hasNext()) { FileItem i_n_f = (FileItem) itera.next(); if (i_n_f.isFormField()) { String nombre = i_n_f.getFieldName(); String valor = i_n_f.getString(); num_filas = (nombre.equals("num")) ? Integer.parseInt(valor) : num_filas; if (nombre.equals("iddgp") & iddgp == null) { iddgp = valor; } if (nombre.equals("idtr") & idtr == null) { idtr = valor; } if (nombre.equals("P2") & pr == null) { pr = valor; } if (nombre.equals("idctr") & id_ctr == null) { id_ctr = valor; } } } String iddoc = null; String nombre_archivo = null; String desc = null; String estado = null; String archivo = null; int num = 0; String no_original = null; String validar_nombre = ""; Random rnd = new Random(); for (int i = 0; i < num_filas; i++) { Iterator it = p.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (item.isFormField()) { String nombre = item.getFieldName(); String valor = item.getString(); iddoc = (nombre.equals("iddoc" + i)) ? valor : iddoc; desc = (nombre.equals("lob_description" + i)) ? valor : desc; estado = (nombre.equals("estado" + i)) ? valor : estado; id_h = (nombre.equals("idh" + i)) ? valor : id_h; } else { String fieldName = item.getFieldName(); num++; Calendar fecha = new GregorianCalendar(); int hora = fecha.get(Calendar.HOUR_OF_DAY); int min = fecha.get(Calendar.MINUTE); int sec = fecha.get(Calendar.SECOND); if (fieldName.equals("archivos" + i) & item.getName() != null) { if (!item.getName().equals("")) { // out.println(item.getFieldName() + " : " + item.getName()); // nombre_archivo = String.valueOf(hora) + String.valueOf(min) + String.valueOf(sec) + "_" + num + iddgp + "_" + item.getName().toUpperCase(); nombre_archivo = String.valueOf(hora) + String.valueOf(min) + String.valueOf(sec) + "_" + num + iddgp; no_original = item.getName(); Thread thread = new Thread(new Renombrar(item, ubicacion, nombre_archivo)); thread.start(); archivo = no_original + ":" + nombre_archivo; list_files.add(archivo); } } else { no_original = no_original; nombre_archivo = nombre_archivo; } } } Thread.sleep(100); if (nombre_archivo != null) { if (!nombre_archivo.equals("")) { estado = ((estado == null) ? "0" : estado); out.println(iddoc); String id = d.INSERT_DOCUMENTO_ADJUNTO(null, iddoc, "1", user, null, null, null, null, desc, null, estado, id_ctr); d.INSERT_DGP_DOC_ADJ(null, iddgp, id, null, idtr, id_h); for (int t = 0; t < list_files.size(); t++) { String g[] = list_files.get(t).split(":"); d.INSERT_ARCHIVO_DOCUMENTO(null, id, g[1], g[0], null); } list_files.clear(); } } no_original = null; iddoc = null; nombre_archivo = null; desc = null; estado = null; no_original = null; } sesion.setAttribute("List_doc_req_pla", d.List_doc_req_pla(iddgp, idtr)); int s = d.List_Req_nacionalidad(idtr); int num_ad = d.List_Adventista(idtr); sesion.setAttribute("List_Hijos", d.List_Hijos(idtr)); sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr)); if (pr != null) { if (pr.equals("enter")) { response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad=" + num_ad + "&P2=TRUE&idtr=" + idtr + "&iddgp=" + iddgp + "&a=t"); } } else { response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad=" + num_ad + "&idtr=" + idtr + "&iddgp=" + iddgp + "&a=t"); } } } catch (Exception e) { out.println("Error : " + e.getMessage()); } finally { out.close(); } }
From source file:pe.edu.upeu.application.web.controller.Cdocumento_adjunto.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException, InterruptedException { response.setContentType("text/html;charset=UTF-8"); String dgp = request.getParameter("iddgp"); String idtr = request.getParameter("idtr"); String idctr = request.getParameter("idctr"); String opc = request.getParameter("opc"); HttpSession sesion = request.getSession(true); String user = (String) sesion.getAttribute("IDUSER"); PrintWriter out = response.getWriter(); // try (PrintWriter out = response.getWriter()) { if (opc != null) { if (opc.equals("Eliminar")) { String id_c = request.getParameter("idc"); c.Eliminar_Contratos_firmados(id_c); int coun_doc = c.Count_doc_con(request.getParameter("idc")); response.sendRedirect("Vista/Contrato/Formato_Plantilla/Subir_Contrato_Firmado.jsp?idc=" + id_c + "&coun_doc=" + coun_doc); //out.print(coun_doc + id_c); }//from w w w . j av a2 s . com } else { String ubicacion = FactoryConnectionDB.url + "/Contratos_Adjuntos/"; System.out.println("Enter to Save Contrato"); DiskFileItemFactory f = new DiskFileItemFactory(); f.setSizeThreshold(1024); f.setRepository(new File(ubicacion)); ServletFileUpload upload = new ServletFileUpload(f); ServletRequestContext src = new ServletRequestContext(request); // try { List<FileItem> p = upload.parseRequest(src); int num_filas = 0; String idc = null; List<String> list_files = new ArrayList<String>(); Iterator itera = p.iterator(); while (itera.hasNext()) { FileItem i_n_f = (FileItem) itera.next(); if (i_n_f.isFormField()) { String nombre = i_n_f.getFieldName(); String valor = i_n_f.getString(); num_filas = (nombre.equals("num")) ? Integer.parseInt(valor) : num_filas; if (nombre.equals("idc") & idc == null) { idc = valor; } } } String nombre_archivo = null; String estado = null; String archivo = null; int num = 0; String no_original = null; Iterator it = p.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (item.isFormField()) { String nombre = item.getFieldName(); } else { String fieldName = item.getFieldName(); num++; Calendar fecha = new GregorianCalendar(); int hora = fecha.get(Calendar.HOUR_OF_DAY); int min = fecha.get(Calendar.MINUTE); int sec = fecha.get(Calendar.SECOND); if (fieldName.equals("archivo") & item.getName() != null) { if (!item.getName().equals("")) { // out.println(item.getFieldName() + " : " + item.getName()); nombre_archivo = String.valueOf(hora) + String.valueOf(min) + String.valueOf(sec) + "_" + num + idc + "_" + item.getName().toUpperCase(); no_original = item.getName(); Thread thread = new Thread(new Renombrar(item, ubicacion, nombre_archivo)); thread.start(); archivo = no_original + ":" + nombre_archivo; list_files.add(archivo); } } else { no_original = no_original; nombre_archivo = nombre_archivo; } out.print(no_original); if (nombre_archivo != null) { if (!nombre_archivo.equals("")) { estado = ((estado == null) ? "0" : estado); for (int t = 0; t < list_files.size(); t++) { c.INSERT_CONTRATO_ADJUNTO(null, idc, nombre_archivo, no_original, null, null, null, null, null, null); String g[] = list_files.get(t).split(":"); } list_files.clear(); } } no_original = null; estado = null; no_original = null; } } Thread.sleep(2000); int coun_doc = c.Count_doc_con(idc); if (coun_doc > 0) { response.sendRedirect("Vista/Contrato/Formato_Plantilla/Subir_Contrato_Firmado.jsp?idc=" + idc + "&coun_doc=" + coun_doc); } else { response.sendRedirect("Vista/Contrato/Formato_Plantilla/Subir_Contrato_Firmado.jsp?idc=" + idc + "&coun_doc=" + coun_doc); } } // } }