List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold
public void setSizeThreshold(int sizeThreshold)
From source file:com.intranet.intr.inbox.SupControllerInbox.java
@RequestMapping(value = "enviarMailA.htm", method = RequestMethod.POST) public String enviarMailA_post(@ModelAttribute("correo") correoNoLeidos c, BindingResult result, HttpServletRequest request) {/*from ww w . j a va 2s . c om*/ String mensaje = ""; try { //MultipartFile multipart = c.getArchivo(); System.out.println("olaEnviarMAILS"); String ubicacionArchivo = "C:\\DecorakiaReportesIntranet\\archivosMail\\"; //File file=new File(ubicacionArchivo,multipart.getOriginalFilename()); //String ubicacionArchivo="C:\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { System.out.println("NOMBRE FOTO: " + item.getName()); File file = new File(ubicacionArchivo, item.getName()); item.write(file); arc.add(item.getName()); System.out.println("img" + item.getName()); } //c.setImagenes(arc); } catch (Exception ex) { } return "redirect:enviarMail.htm"; }
From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java
public void execute(ActionRequest actionRequest, ActionResponse actionResponse) { try {//from w ww .j a v a 2 s . co m sCheckPermissions(actionRequest); String portletId = "_" + PortalUtil.getPortletId(actionRequest) + "_"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(100 * 1024 * 1024); PortletFileUpload upload = new PortletFileUpload(factory); FileItem fileUploaded = null; List<FileItem> items = upload.parseRequest(actionRequest); for (FileItem fi : items) { if (fi.isFormField()) { actionRequest.setAttribute(fi.getFieldName(), fi.getString()); if (fi.getFieldName().startsWith(portletId)) { actionRequest.setAttribute(fi.getFieldName().substring(portletId.length()), fi.getString()); } } else { fileUploaded = fi; } } String cmd = (String) actionRequest.getAttribute("cmd"); String language = (String) actionRequest.getAttribute("language"); String script = (String) actionRequest.getAttribute("script"); String editorheight = (String) actionRequest.getAttribute("editorheight"); String themesel = (String) actionRequest.getAttribute("themesel"); if (language == null) { language = getDefaultLanguage(); } if (script == null) { script = StringPool.BLANK; } actionResponse.setRenderParameter("language", language); actionResponse.setRenderParameter("script", script); actionResponse.setRenderParameter("editorheight", editorheight); actionResponse.setRenderParameter("themesel", themesel); if ("execute".equals(cmd)) { Map<String, Object> portletObjects = ScriptingHelperUtil.getPortletObjects(getPortletConfig(), getPortletContext(), actionRequest, actionResponse); UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(); UnsyncPrintWriter unsyncPrintWriter = UnsyncPrintWriterPool.borrow(unsyncByteArrayOutputStream); portletObjects.put("out", unsyncPrintWriter); _log.info("Executing script"); ScriptingUtil.exec(null, portletObjects, language, script, StringPool.EMPTY_ARRAY); unsyncPrintWriter.flush(); actionResponse.setRenderParameter("script_output", unsyncByteArrayOutputStream.toString()); } else if ("save".equals(cmd)) { String newscriptname = (String) actionRequest.getAttribute("newscriptname"); if (newscriptname == null || newscriptname.trim().length() == 0) { actionResponse.setRenderParameter("script_trace", "No script name specified to save into!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Saving new script: " + newscriptname.trim()); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + newscriptname.trim(), script); prefs.setValue("lang." + newscriptname.trim(), language); prefs.store(); } else if ("saveinto".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to save into!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Saving saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + scriptname, script); prefs.setValue("lang." + scriptname, language); prefs.store(); } else if ("loadfrom".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to load from!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Loading saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); language = prefs.getValue("lang." + scriptname, getDefaultLanguage()); script = prefs.getValue("savedscript." + scriptname, StringPool.BLANK); actionResponse.setRenderParameter("language", language); actionResponse.setRenderParameter("script", script); } else if ("delete".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to delete!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Deleting saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); prefs.reset("savedscript." + scriptname); prefs.reset("lang." + scriptname); prefs.store(); } else if ("import".equals(cmd)) { if (fileUploaded == null) { actionResponse.setRenderParameter("script_trace", "No file was uploaded for import!"); SessionErrors.add(actionRequest, "error"); return; } StringBuilder output = new StringBuilder(); InputStream instream = fileUploaded.getInputStream(); ZipInputStream zipstream = null; try { zipstream = new ZipInputStream(instream); ZipEntry entry = zipstream.getNextEntry(); while (entry != null) { String filename = entry.getName(); if (filename.contains("/")) { int qs = filename.lastIndexOf("/"); if (qs != -1) { filename = filename.substring(qs + 1); } } if (filename.contains("\\")) { int qs = filename.lastIndexOf("\\"); if (qs != -1) { filename = filename.substring(qs + 1); } } String ext = StringPool.BLANK; if (filename.length() > 0) { int qs = filename.lastIndexOf("."); if (qs > 0) { ext = filename.substring(qs + 1); filename = filename.substring(0, qs); } } String lang = resolveLanguage(ext); String imscript = getStreamAsString(zipstream, "utf-8", false); if (imscript != null && imscript.length() > 0) { _log.info("Importing script \"" + filename + "\" of type " + lang); output.append("Importing script \"" + filename + "\" of type " + lang + "\n"); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + filename, imscript); prefs.setValue("lang." + filename, lang); prefs.store(); } entry = zipstream.getNextEntry(); } actionResponse.setRenderParameter("script_output", output.toString()); } finally { try { if (zipstream != null) { zipstream.close(); } } catch (Exception e) { } try { if (instream != null) { instream.close(); } } catch (Exception e) { } } _log.info(fileUploaded.getName()); } SessionMessages.add(actionRequest, "success"); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.close(); actionResponse.setRenderParameter("script_trace", sw.toString()); _log.error(e); SessionErrors.add(actionRequest, e.toString()); } }
From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java
/** * Sets up the given {@link PostMethod} to send the same multipart POST * data as was sent in the given {@link HttpServletRequest} * @param postMethodProxyRequest The {@link PostMethod} that we are * configuring to send a multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains * the mutlipart POST data to be sent via the {@link PostMethod} */// w ww . j a v a 2 s. c om @SuppressWarnings("unchecked") private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws IOException { _log.debug("handleMultipartPost()"); // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(HttpConstants.STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new IOException(fileUploadException); } }
From source file:com.mx.nibble.middleware.web.util.FileUpload.java
public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) { /**/* ww w . ja v a 2s .com*/ * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org. * * Note: * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. * * * * * * */ logger.debug(" Directory to store all the uploaded files"); String ourTempDirectory = "/opt/erp/import/obras/"; try { out = response.getWriter(); } catch (Exception e) { e.printStackTrace(); } byte[] cr = { 13 }; byte[] lf = { 10 }; String CR = new String(cr); String LF = new String(lf); String CRLF = CR + LF; out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF); logger.debug("Initialization for chunk management."); boolean bLastChunk = false; int numChunk = 0; logger.debug( "CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL"); boolean generateError = false; boolean generateWarning = false; boolean sendRequest = false; response.setContentType("text/plain"); java.util.Enumeration<String> headers = request.getHeaderNames(); out.println("[parseRequest.jsp] ------------------------------ "); out.println("[parseRequest.jsp] Headers of the received request:"); logger.debug("[parseRequest.jsp] Headers of the received request:"); while (headers.hasMoreElements()) { String header = headers.nextElement(); out.println("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); logger.debug("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); } out.println("[parseRequest.jsp] ------------------------------ "); try { logger.debug(" Get URL Parameters."); Enumeration paraNames = request.getParameterNames(); out.println("[parseRequest.jsp] ------------------------------ "); out.println("[parseRequest.jsp] Parameters: "); logger.debug("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = request.getParameter(pname); out.println("[parseRequest.jsp] " + pname + " = " + pvalue); logger.debug("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { numChunk = Integer.parseInt(pvalue); } if (pname.equals("error") && pvalue.equals("true")) { generateError = true; logger.debug( "For debug convenience, putting error=true as a URL parameter, will generate an error in this response."); } if (pname.equals("warning") && pvalue.equals("true")) { generateWarning = true; logger.debug( "For debug convenience, putting warning=true as a URL parameter, will generate a warning in this response."); } if (pname.equals("sendRequest") && pvalue.equals("true")) { sendRequest = true; logger.debug( "For debug convenience, putting readRequest=true as a URL parameter, will send back the request content into the response of this page."); } } out.println("[parseRequest.jsp] ------------------------------ "); int ourMaxMemorySize = 10000000; int ourMaxRequestSize = 2000000000; /////////////////////////////////////////////////////////////////////////////////////////////////////// //The code below is directly taken from the jakarta fileupload common classes //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/ /////////////////////////////////////////////////////////////////////////////////////////////////////// logger.debug(" Create a factory for disk-based file items"); DiskFileItemFactory factory = new DiskFileItemFactory(); logger.debug(" Set factory constraints"); factory.setSizeThreshold(ourMaxMemorySize); logger.debug("ourTempDirectory" + ourTempDirectory); factory.setRepository(new File(ourTempDirectory)); logger.debug(" Create a new file upload handler"); ServletFileUpload upload = new ServletFileUpload(factory); logger.debug(" Set overall request size constraint"); upload.setSizeMax(ourMaxRequestSize); logger.debug(" Parse the request"); if (sendRequest) { logger.debug("For debug only. Should be removed for production systems. "); out.println( "[parseRequest.jsp] ==========================================================================="); out.println("[parseRequest.jsp] Sending the received request content: "); logger.debug("[parseRequest.jsp] Sending the received request content: "); InputStream is = request.getInputStream(); int c; while ((c = is.read()) >= 0) { out.write(c); } logger.debug("while"); is.close(); out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!request.getContentType().startsWith("multipart/form-data")) { out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + request.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(request); logger.debug(" Process the uploaded items" + items.size()); Iterator iter = items.iterator(); FileItem fileItem; File fout; out.println("[parseRequest.jsp] Let's read the sent data (" + items.size() + " items)"); while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = " + fileItem.getString()); logger.debug( "If we receive the md5sum parameter, we've read finished to read the current file. It's not"); logger.debug( "a very good (end of file) signal. Will be better in the future ... probably !"); logger.debug("Let's put a separator, to make output easier to read."); if (fileItem.getFieldName().equals("md5sum[]")) { out.println("[parseRequest.jsp] ------------------------------ "); } } else { logger.debug("Ok, we've got a file. Let's process it."); logger.debug("Again, for all informations of what is exactly a FileItem, please"); logger.debug("have a look to http://jakarta.apache.org/commons/fileupload/"); out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName()); out.println("[parseRequest.jsp] File Name: " + fileItem.getName()); out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType()); out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize()); logger.debug( "If we are in chunk mode, we add .partN at the end of the file, where N is the chunk number."); String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : ""); fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName()); out.println("[parseRequest.jsp] File Out: " + fout.toString()); logger.debug(" write the file"); fileItem.write(fout); // logger.debug("Chunk management: if it was the last chunk, let's recover the complete file"); logger.debug("by concatenating all chunk parts."); logger.debug(""); if (bLastChunk) { out.println("[parseRequest.jsp] Last chunk received: let's rebuild the complete file (" + fileItem.getName() + ")"); logger.debug("First: construct the final filename."); FileInputStream fis; FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName()); int nbBytes; byte[] byteBuff = new byte[1024]; String filename; for (int i = 1; i <= numChunk; i += 1) { filename = fileItem.getName() + ".part" + i; out.println("[parseRequest.jsp] " + " Concatenating " + filename); fis = new FileInputStream(ourTempDirectory + filename); while ((nbBytes = fis.read(byteBuff)) >= 0) { //out.println("[parseRequest.jsp] " + " Nb bytes read: " + nbBytes); fos.write(byteBuff, 0, nbBytes); } fis.close(); } fos.close(); } logger.debug(" End of chunk management"); // fileItem.delete(); } } logger.debug("while"); } if (generateWarning) { out.println("WARNING: just a warning message.\\nOn two lines!"); } out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :"); logger.debug("Let's wait a little, to simulate the server time to manage the file."); Thread.sleep(500); logger.debug("Do you want to test a successful upload, or the way the applet reacts to an error ?"); if (generateError) { out.println( "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!"); } else { out.println("SUCCESS"); logger.debug(""); } out.println("[parseRequest.jsp] " + "End of server treatment "); } catch (Exception e) { out.println(""); out.println("ERROR: Exception e = " + e.toString()); out.println(""); } }
From source file:com.globalsight.everest.webapp.pagehandler.administration.mtprofile.MTProfileImportHandler.java
/** * Upload the properties file to FilterConfigurations/import folder * // www.j ava 2 s . c om * @param request */ private File uploadFile(HttpServletRequest request) { File f = null; try { String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight" + File.separator + "MachineTranslationProfiles" + File.separator + "import"; boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024000); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (!item.isFormField()) { String filePath = item.getName(); if (filePath.contains(":")) { filePath = filePath.substring(filePath.indexOf(":") + 1); } String originalFilePath = filePath.replace("\\", File.separator).replace("/", File.separator); String fileName = tmpDir + File.separator + originalFilePath; f = new File(fileName); f.getParentFile().mkdirs(); item.write(f); } } } return f; } catch (Exception e) { logger.error("File upload failed.", e); return null; } }
From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java
private Vector uploadTmpAttachmentFile(HttpServletRequest request, HttpSession session) { String tmpFoler = request.getParameter("folder"); String uploadPath = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight" + File.separator + "CommentReference" + File.separator + "tmp" + File.separator + tmpFoler; try {/* w ww .j av a 2 s.c o m*/ boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024000); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { DiskFileItem item = (DiskFileItem) items.get(i); if (!item.isFormField()) { String fileName = item.getFieldName(); String filePath = uploadPath + File.separator + fileName; File f = new File(filePath); f.getParentFile().mkdirs(); item.write(f); } } } } catch (Exception e) { throw new EnvoyServletException(e); } return new Vector(); }
From source file:com.mx.nibble.middleware.web.util.FileUploadOLD.java
public String execute() throws Exception { //ActionContext ac = invocation.getInvocationContext(); HttpServletResponse response = ServletActionContext.getResponse(); // MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest()); HttpServletRequest multipartRequest = ServletActionContext.getRequest(); List<FileItem> items2 = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartRequest); System.out.println("TAMAO ITEMS " + items2.size()); System.out.println("Check that we have a file upload request"); boolean isMultipart = ServletFileUpload.isMultipartContent(multipartRequest); System.out.println("isMultipart: " + isMultipart); String ourTempDirectory = "/opt/erp/import/obras/"; byte[] cr = { 13 }; byte[] lf = { 10 }; String CR = new String(cr); String LF = new String(lf); String CRLF = CR + LF;/*from www . ja v a2s .c om*/ System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF); //Initialization for chunk management. boolean bLastChunk = false; int numChunk = 0; //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL boolean generateError = false; boolean generateWarning = false; boolean sendRequest = false; response.setContentType("text/plain"); java.util.Enumeration<String> headers = multipartRequest.getHeaderNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Headers of the received request:"); while (headers.hasMoreElements()) { String header = headers.nextElement(); System.out.println("[parseRequest.jsp] " + header + ": " + multipartRequest.getHeader(header)); } System.out.println("[parseRequest.jsp] ------------------------------ "); try { System.out.println(" Get URL Parameters."); Enumeration paraNames = multipartRequest.getParameterNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = multipartRequest.getParameter(pname); System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { System.out.println("pname.equals(\"jufinal\")"); bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { System.out.println("pname.equals(\"jupart\")"); numChunk = Integer.parseInt(pvalue); } //For debug convenience, putting error=true as a URL parameter, will generate an error //in this response. if (pname.equals("error") && pvalue.equals("true")) { generateError = true; } //For debug convenience, putting warning=true as a URL parameter, will generate a warning //in this response. if (pname.equals("warning") && pvalue.equals("true")) { generateWarning = true; } //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content //into the response of this page. if (pname.equals("sendRequest") && pvalue.equals("true")) { sendRequest = true; } } System.out.println("[parseRequest.jsp] ------------------------------ "); int ourMaxMemorySize = 10000000; int ourMaxRequestSize = 2000000000; /////////////////////////////////////////////////////////////////////////////////////////////////////// //The code below is directly taken from the jakarta fileupload common classes //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(ourMaxMemorySize); factory.setRepository(new File(ourTempDirectory)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(ourMaxRequestSize); // Parse the request if (sendRequest) { //For debug only. Should be removed for production systems. System.out.println( "[parseRequest.jsp] ==========================================================================="); System.out.println("[parseRequest.jsp] Sending the received request content: "); InputStream is = multipartRequest.getInputStream(); int c; while ((c = is.read()) >= 0) { System.out.write(c); } //while is.close(); System.out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!multipartRequest.getContentType().startsWith("multipart/form-data")) { System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + multipartRequest.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(multipartRequest); // Process the uploaded items Iterator iter = items.iterator(); FileItem fileItem; File fout; System.out.println("[parseRequest.jsp] Let's read the sent data (" + items.size() + " items)"); while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = " + fileItem.getString()); //If we receive the md5sum parameter, we've read finished to read the current file. It's not //a very good (end of file) signal. Will be better in the future ... probably ! //Let's put a separator, to make output easier to read. if (fileItem.getFieldName().equals("md5sum[]")) { System.out.println("[parseRequest.jsp] ------------------------------ "); } } else { //Ok, we've got a file. Let's process it. //Again, for all informations of what is exactly a FileItem, please //have a look to http://jakarta.apache.org/commons/fileupload/ // System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName()); System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName()); System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType()); System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize()); //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number. String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : ""); fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName()); System.out.println("[parseRequest.jsp] File Out: " + fout.toString()); System.out.println(" write the file"); fileItem.write(fout); ////////////////////////////////////////////////////////////////////////////////////// System.out.println( " Chunk management: if it was the last chunk, let's recover the complete file"); System.out.println(" by concatenating all chunk parts."); // if (bLastChunk) { System.out.println( "[parseRequest.jsp] Last chunk received: let's rebuild the complete file (" + fileItem.getName() + ")"); //First: construct the final filename. FileInputStream fis; FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName()); int nbBytes; byte[] byteBuff = new byte[1024]; String filename; for (int i = 1; i <= numChunk; i += 1) { filename = fileItem.getName() + ".part" + i; System.out.println("[parseRequest.jsp] " + " Concatenating " + filename); fis = new FileInputStream(ourTempDirectory + filename); while ((nbBytes = fis.read(byteBuff)) >= 0) { //out.println("[parseRequest.jsp] " + " Nb bytes read: " + nbBytes); fos.write(byteBuff, 0, nbBytes); } fis.close(); } fos.close(); } // End of chunk management ////////////////////////////////////////////////////////////////////////////////////// fileItem.delete(); } } //while } if (generateWarning) { System.out.println("WARNING: just a warning message.\\nOn two lines!"); } System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :"); //Let's wait a little, to simulate the server time to manage the file. Thread.sleep(500); //Do you want to test a successful upload, or the way the applet reacts to an error ? if (generateError) { System.out.println( "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!"); } else { System.out.println("SUCCESS"); //out.println(" <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>"); } System.out.println("[parseRequest.jsp] " + "End of server treatment "); } catch (Exception e) { System.out.println(""); System.out.println("ERROR: Exception e = " + e.toString()); System.out.println(""); } return SUCCESS; }
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Sets up the given {@link EntityEnclosingMethod} to send the same multipart * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are * configuring to send a multipart request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the mutlipart data to be sent via the {@link EntityEnclosingMethod} *///from www. j a v a2 s . co m private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws ServletException { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), entityEnclosingMethod.getParams()); entityEnclosingMethod.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java
private Vector uploadTmpFiles(HttpServletRequest request, HttpSession session) { String tmpFoler = request.getParameter("folder"); String uploadPath = AmbFileStoragePathUtils.getCxeDocDir() + File.separator + CreateJobsMainHandler.TMP_FOLDER_NAME + File.separator + tmpFoler; try {/*from w w w .j a v a2 s .co m*/ boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024000); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { DiskFileItem item = (DiskFileItem) items.get(i); if (!item.isFormField()) { String filePath = item.getFieldName(); if (filePath.contains(":")) { filePath = filePath.substring(filePath.indexOf(":") + 1); } String originalFilePath = filePath.replace("\\", File.separator).replace("/", File.separator); String fileName = uploadPath + File.separator + originalFilePath; File f = new File(fileName); f.getParentFile().mkdirs(); item.write(f); String extension = FileUtils.getFileExtension(f); if (extension != null && extension.equalsIgnoreCase("zip")) { unzipFile(f); f.delete(); } } } } } catch (Exception e) { throw new EnvoyServletException(e); } return new Vector(); }
From source file:com.example.web.Create_story.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); int count = 1; String storyid, storystep;//www .j a v a 2 s. c o m String fileName = ""; int f = 0; String action = ""; String first = request.getParameter("first"); String user = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) user = cookie.getValue(); } } String title = request.getParameter("title"); String header = request.getParameter("header"); String text_field = request.getParameter("text_field"); String latitude = request.getParameter("lat"); String longitude = request.getParameter("lng"); storyid = (request.getParameter("storyid")); storystep = (request.getParameter("storystep")); String message = ""; int valid = 1; String query; ResultSet rs; Connection conn; String url = "jdbc:mysql://localhost:3306/"; String dbName = "tworld"; String driver = "com.mysql.jdbc.Driver"; isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { 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("/var/lib/tomcat7/webapps/www_term_project/temp/")); 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.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); 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(); String[] spliting = fileName.split("\\."); // Write the file System.out.println(sizeInBytes + " " + maxFileSize); System.out.println(spliting[spliting.length - 1]); if (!fileName.equals("")) { if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg") || spliting[spliting.length - 1].equals("png") || spliting[spliting.length - 1].equals("jpeg"))) { 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); System.out.println("Uploaded Filename: " + fileName + "<br>"); } else { valid = 0; message = "not a valid image"; } } } BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(fi.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } if (f == 0) action = sb.toString(); else if (f == 1) storyid = sb.toString(); else if (f == 2) storystep = sb.toString(); else if (f == 3) title = sb.toString(); else if (f == 4) header = sb.toString(); else if (f == 5) text_field = sb.toString(); else if (f == 6) latitude = sb.toString(); else if (f == 7) longitude = sb.toString(); else if (f == 8) first = sb.toString(); f++; } } catch (Exception ex) { System.out.println("hi"); System.out.println(ex); } } if (latitude == null) latitude = ""; if (latitude.equals("") && first == null) { request.setAttribute("message", "please enter a marker"); request.setAttribute("storyid", storyid); request.setAttribute("s_page", "3"); request.setAttribute("storystep", storystep); request.getRequestDispatcher("/index.jsp").forward(request, response); } else if (valid == 1) { try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url + dbName, "admin", "admin"); if (first != null) { if (first.equals("first_step")) { do { query = "select * from story_database where story_id='" + count + "' "; Statement st = conn.createStatement(); rs = st.executeQuery(query); count++; } while (rs.next()); int a = count - 1; request.setAttribute("storyid", a); storyid = Integer.toString(a); request.setAttribute("storystep", 2); } } query = "select * from story_database where `story_id`='" + storyid + "' && `step_num`='" + storystep + "' "; Statement st = conn.createStatement(); rs = st.executeQuery(query); if (!rs.next()) { PreparedStatement pst = (PreparedStatement) conn.prepareStatement( "insert into `tworld`.`story_database`(`story_id`, `step_num`, `content`, `latitude`, `longitude`, `title`, `header`, `max_steps`, `username`,`image_name`) values(?,?,?,?,?,?,?,?,?,?)"); pst.setInt(1, Integer.parseInt(storyid)); pst.setInt(2, Integer.parseInt(storystep)); pst.setString(3, text_field); pst.setString(4, latitude); pst.setString(5, longitude); pst.setString(6, title); pst.setString(7, header); pst.setInt(8, Integer.parseInt(storystep)); pst.setString(9, user); if (fileName.equals("")) pst.setString(10, ""); else pst.setString(10, fileName); pst.executeUpdate(); pst.close(); pst = (PreparedStatement) conn.prepareStatement( "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?"); pst.setInt(1, Integer.parseInt(storystep)); pst.setInt(2, Integer.parseInt(storyid)); pst.executeUpdate(); pst.close(); } else { PreparedStatement pst = (PreparedStatement) conn.prepareStatement( "UPDATE `tworld`.`story_database` SET `content`=?, `latitude`=?, `longitude`=?, `title`=?, `header`=?, `max_steps`=?, `username`=? WHERE `story_id` = ? && `step_num`=?"); pst.setString(1, text_field); pst.setString(2, latitude); pst.setString(3, longitude); pst.setString(4, title); pst.setString(5, header); pst.setInt(6, Integer.parseInt(storystep)); pst.setString(7, user); pst.setInt(8, Integer.parseInt(storyid)); pst.setInt(9, Integer.parseInt(storystep)); pst.executeUpdate(); pst.close(); pst = (PreparedStatement) conn.prepareStatement( "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?"); pst.setInt(1, Integer.parseInt(storystep)); pst.setInt(2, Integer.parseInt(storyid)); pst.executeUpdate(); pst.close(); } request.setAttribute("storyid", storyid); storystep = Integer.toString(Integer.parseInt(storystep) + 1); request.setAttribute("storystep", storystep); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { // Logger.getLogger(MySignInServlet.class.getName()).log(Level.SEVERE, null, ex); } request.setAttribute("s_page", "3"); request.getRequestDispatcher("/index.jsp").forward(request, response); } else { request.setAttribute("storyid", storyid); request.setAttribute("message", message); request.setAttribute("storystep", storystep); request.setAttribute("s_page", "3"); request.getRequestDispatcher("/index.jsp").forward(request, response); } }