List of usage examples for org.apache.commons.fileupload DiskFileUpload DiskFileUpload
public DiskFileUpload()
FileItem
instances. From source file:org.bootchart.servlet.RenderServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { File logTmpFile = null;/*from w ww . j av a2 s . c o m*/ try { DiskFileUpload fu = new DiskFileUpload(); // maximum size before a FileUploadException will be thrown fu.setSizeMax(32 * 1024 * 1024); fu.setSizeThreshold(4 * 1024 * 1024); fu.setRepositoryPath(TEMP_DIR); String format = "png"; List fileItems = fu.parseRequest(request); File tmpFile = File.createTempFile("file.", ".tmp"); String tmpName = tmpFile.getName().substring(5, tmpFile.getName().length() - 4); tmpFile.delete(); for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem fi = (FileItem) i.next(); String name = fi.getName(); if (name == null || name.length() == 0) { if ("format".equals(fi.getFieldName())) { format = fi.getString(); } continue; } if (name.indexOf("bootchart") != -1) { String suffix = ""; if (name.endsWith(".tar.gz")) { suffix = ".tar.gz"; } else { suffix = name.substring(name.lastIndexOf('.')); } logTmpFile = new File(TEMP_DIR, "bootchart." + tmpName + suffix); fi.write(logTmpFile); } } if (logTmpFile == null || !logTmpFile.exists()) { writeError(response, LOG_FORMAT_ERROR, null); log.severe("No log tarball provided"); return; } // Render PNG by default if (format == null) { format = "png"; } boolean prune = true; new File(TEMP_DIR + "/images").mkdirs(); String tmpImgFileName = TEMP_DIR + "/images/" + "bootchart." + tmpName; File tmpImgFile = null; try { tmpImgFileName = Main.render(logTmpFile, format, prune, tmpImgFileName); tmpImgFile = new File(tmpImgFileName); FileInputStream fis = new FileInputStream(tmpImgFileName); OutputStream os = response.getOutputStream(); String contentType = "application/octet-stream"; String suffix = ""; if ("png".equals(format)) { contentType = "image/png"; suffix = new PNGRenderer().getFileSuffix(); } else if ("svg".equals(format)) { contentType = "image/svg+xml"; suffix = new SVGRenderer().getFileSuffix(); } else if ("eps".equals(format)) { contentType = "image/eps"; suffix = new EPSRenderer().getFileSuffix(); } response.setContentType(contentType); response.setHeader("Content-disposition", "attachment; filename=bootchart." + suffix); byte[] buff = new byte[4096]; while (true) { int read = fis.read(buff); if (read < 0) { break; } os.write(buff, 0, read); os.flush(); } fis.close(); } finally { if (tmpImgFile != null && !tmpImgFile.delete()) { tmpImgFile.deleteOnExit(); } } } catch (Exception e) { writeError(response, null, e); log.log(Level.SEVERE, "", e); } if (logTmpFile != null && !logTmpFile.delete()) { logTmpFile.deleteOnExit(); } }
From source file:org.chiba.adapter.web.HttpRequestHandler.java
/** * @param request Servlet request/*from www . ja va 2 s. com*/ * @param trigger Trigger control * @return the calculated trigger * @throws XFormsException If an error occurs */ protected String processMultiPartRequest(HttpServletRequest request, String trigger) throws XFormsException { DiskFileUpload upload = new DiskFileUpload(); String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "ISO-8859-1"; } upload.setRepositoryPath(this.uploadRoot); if (LOGGER.isDebugEnabled()) { LOGGER.debug("root dir for uploads: " + this.uploadRoot); } List items; try { items = upload.parseRequest(request); } catch (FileUploadException fue) { throw new XFormsException(fue); } Map formFields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String itemName = item.getName(); String fieldName = item.getFieldName(); String id = fieldName.substring(Config.getInstance().getProperty("chiba.web.dataPrefix").length()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Multipart item name is: " + itemName + " and fieldname is: " + fieldName + " and id is: " + id); LOGGER.debug("Is formfield: " + item.isFormField()); LOGGER.debug("Content: " + item.getString()); } if (item.isFormField()) { // check for upload-remove action if (fieldName.startsWith(getRemoveUploadPrefix())) { id = fieldName.substring(getRemoveUploadPrefix().length()); // if data is null, file will be removed ... // TODO: remove the file from the disk as well chibaBean.updateControlValue(id, "", "", null); continue; } // It's a field name, it means that we got a non-file // form field. Upload is not required. We must treat it as we // do in processUrlencodedRequest() processMultipartParam(formFields, fieldName, item, encoding); } else { String uniqueFilename = new File(getUniqueParameterName("file"), new File(itemName).getName()) .getPath(); File savedFile = new File(this.uploadRoot, uniqueFilename); byte[] data = null; data = processMultiPartFile(item, id, savedFile, encoding, data); // if data is null, file will be removed ... // TODO: remove the file from the disk as well chibaBean.updateControlValue(id, item.getContentType(), itemName, data); } // handle regular fields if (formFields.size() > 0) { Iterator it = formFields.keySet().iterator(); while (it.hasNext()) { fieldName = (String) it.next(); String[] values = (String[]) formFields.get(fieldName); // [1] handle data handleData(fieldName, values); // [2] handle selector handleSelector(fieldName, values[0]); // [3] handle trigger trigger = handleTrigger(trigger, fieldName); } } } return trigger; }
From source file:org.craft.xdd.view.servlet.FCKEditorUploaderServlet.java
/** * Manage the Upload requests.<br> * /*from ww w. j a v a 2s .c o m*/ * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("--- FCKEditorUploaderServlet BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String typeStr = request.getParameter("Type"); String currentPath = baseDir + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; log.debug(currentDirPath); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new DiskFileUpload(); upload.setHeaderEncoding("UTF-8"); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else { fields.put(item.getFieldName(), item); } } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = new String(pathParts[pathParts.length - 1].getBytes(), "GBK"); String timeSerial = new Long(System.currentTimeMillis()).toString(); String ext = getExtension(fileName); fileName = timeSerial + "." + ext; File pathToSave = new File(currentDirPath, fileName); fileUrl = currentPath + "/" + fileName; if (extIsAllowed(typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = timeSerial + "(" + counter + ")" + "." + ext; fileUrl = currentPath + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; log.debug("Invalid file type: " + ext); } } catch (Exception ex) { log.debug(ex.getMessage(), ex); retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); log.debug("--- FCKEditorUploaderServlet BEGIN DOPOST ---"); }
From source file:org.exoplatform.frameworks.jcr.command.web.fckeditor.UploadFileCommand.java
public boolean execute(Context context) throws Exception { GenericWebAppContext webCtx = (GenericWebAppContext) context; HttpServletResponse response = webCtx.getResponse(); HttpServletRequest request = webCtx.getRequest(); PrintWriter out = response.getWriter(); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); String type = (String) context.get("Type"); if (type == null) { type = ""; }//from w w w .j a va2 s . c o m // // To limit browsing set Servlet init param "digitalAssetsPath" // // with desired JCR path // String rootFolderStr = // (String)context.get("org.exoplatform.frameworks.jcr.command.web.fckeditor.digitalAssetsPath" // ); // // if(rootFolderStr == null) // rootFolderStr = "/"; // // // set current folder // String currentFolderStr = (String)context.get("CurrentFolder"); // if(currentFolderStr == null) // currentFolderStr = ""; // else if(currentFolderStr.length() < rootFolderStr.length()) // currentFolderStr = rootFolderStr; // // String jcrMapping = (String)context.get(GenericWebAppContext.JCR_CONTENT_MAPPING); // if(jcrMapping == null) // jcrMapping = DisplayResourceCommand.DEFAULT_MAPPING; // // String digitalWS = (String)webCtx.get(AppConstants.DIGITAL_ASSETS_PROP); // if(digitalWS == null) // digitalWS = AppConstants.DEFAULT_DIGITAL_ASSETS_WS; String workspace = (String) webCtx.get(AppConstants.DIGITAL_ASSETS_PROP); if (workspace == null) { workspace = AppConstants.DEFAULT_DIGITAL_ASSETS_WS; } String currentFolderStr = getCurrentFolderPath(webCtx); webCtx.setCurrentWorkspace(workspace); Node parentFolder = (Node) webCtx.getSession().getItem(currentFolderStr); DiskFileUpload upload = new DiskFileUpload(); List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString()); } else { fields.put(item.getFieldName(), item); } } FileItem uplFile = (FileItem) fields.get("NewFile"); // On IE, the file name is specified as an absolute path. String fileName = uplFile.getName(); if (fileName != null) { int lastUnixPos = fileName.lastIndexOf("/"); int lastWindowsPos = fileName.lastIndexOf("\\"); int index = Math.max(lastUnixPos, lastWindowsPos); fileName = fileName.substring(index + 1); } Node file = JCRCommandHelper.createResourceFile(parentFolder, fileName, uplFile.getInputStream(), uplFile.getContentType()); parentFolder.save(); int retVal = 0; out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + "');"); out.println("</script>"); out.flush(); out.close(); return false; }
From source file:org.exoplatform.services.xmpp.rest.FileExchangeService.java
@POST public Response upload() throws IOException { EnvironmentContext env = EnvironmentContext.getCurrent(); HttpServletRequest req = (HttpServletRequest) env.get(HttpServletRequest.class); HttpServletResponse resp = (HttpServletResponse) env.get(HttpServletResponse.class); String description = req.getParameter("description"); String username = req.getParameter("username"); String requestor = req.getParameter("requestor"); String isRoom = req.getParameter("isroom"); boolean isMultipart = FileUploadBase.isMultipartContent(req); if (isMultipart) { // FileItemFactory factory = new DiskFileUpload(); // Create a new file upload handler // ServletFileUpload upload = new ServletFileUpload(factory); DiskFileUpload upload = new DiskFileUpload(); // Parse the request try {/*from w ww . ja v a2 s. c om*/ List<FileItem> items = upload.parseRequest(req); XMPPMessenger messenger = (XMPPMessenger) PortalContainer.getInstance() .getComponentInstanceOfType(XMPPMessenger.class); for (FileItem fileItem : items) { XMPPSessionImpl session = (XMPPSessionImpl) messenger.getSession(username); String fileName = fileItem.getName(); String fileType = fileItem.getContentType(); if (session != null) { if (fileName != null) { // TODO Check this for compatible or not // It's necessary because IE posts full path of uploaded files fileName = FilenameUtils.getName(fileName); fileType = FilenameUtils.getExtension(fileName); File file = new File(tmpDir); if (file.isDirectory()) { String uuid = UUID.randomUUID().toString(); boolean success = (new File(tmpDir + "/" + uuid)).mkdir(); if (success) { String path = tmpDir + "/" + uuid + "/" + fileName; File f = new File(path); success = f.createNewFile(); if (success) { // File did not exist and was created InputStream inputStream = fileItem.getInputStream(); OutputStream out = new FileOutputStream(f); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); if (log.isDebugEnabled()) log.debug("File " + path + "is created"); session.sendFile(requestor, path, description, Boolean.parseBoolean(isRoom)); } } else { if (log.isDebugEnabled()) log.debug("File already exists"); } } } } else { if (log.isDebugEnabled()) log.debug("XMPPSession for user " + username + " is null!"); } } } catch (Exception e) { if (log.isDebugEnabled()) e.printStackTrace(); return Response.status(HTTPStatus.BAD_REQUEST).entity(e.getMessage()).build(); } } return Response.ok().build(); }
From source file:org.exoplatform.wiki.service.impl.WikiRestServiceImpl.java
@POST @Path("/upload/{wikiType}/{wikiOwner:.+}/{pageId}/") public Response upload(@PathParam("wikiType") String wikiType, @PathParam("wikiOwner") String wikiOwner, @PathParam("pageId") String pageId) { EnvironmentContext env = EnvironmentContext.getCurrent(); HttpServletRequest req = (HttpServletRequest) env.get(HttpServletRequest.class); boolean isMultipart = FileUploadBase.isMultipartContent(req); if (isMultipart) { DiskFileUpload upload = new DiskFileUpload(); // Parse the request try {//from w w w .j a v a2 s .c om List<FileItem> items = upload.parseRequest(req); for (FileItem fileItem : items) { InputStream inputStream = fileItem.getInputStream(); byte[] imageBytes; if (inputStream != null) { imageBytes = new byte[inputStream.available()]; inputStream.read(imageBytes); } else { imageBytes = null; } String fileName = fileItem.getName(); String fileType = fileItem.getContentType(); if (fileName != null) { // It's necessary because IE posts full path of uploaded files fileName = FilenameUtils.getName(fileName); fileType = FilenameUtils.getExtension(fileName); } String mimeType = new MimeTypeResolver().getMimeType(fileName); WikiResource attachfile = new WikiResource(mimeType, "UTF-8", imageBytes); attachfile.setName(fileName); if (attachfile != null) { WikiService wikiService = (WikiService) PortalContainer.getComponent(WikiService.class); Page page = wikiService.getExsitedOrNewDraftPageById(wikiType, wikiOwner, pageId); if (page != null) { AttachmentImpl att = ((PageImpl) page).createAttachment(attachfile.getName(), attachfile); ConversationState conversationState = ConversationState.getCurrent(); String creator = null; if (conversationState != null && conversationState.getIdentity() != null) { creator = conversationState.getIdentity().getUserId(); } att.setCreator(creator); Utils.reparePermissions(att); } } } } catch (Exception e) { log.error(e.getMessage(), e); return Response.status(HTTPStatus.BAD_REQUEST).entity(e.getMessage()).build(); } } return Response.ok().build(); }
From source file:org.hdiv.config.multipart.StrutsMultipartConfig.java
/** * Parses the input stream and partitions the parsed items into a set of form fields and a set of file items. * // w ww.ja va 2 s. c om * @param request * The multipart request wrapper. * @param servletContext * Our ServletContext object * @return multipart processed request * @throws HdivMultipartException * if an unrecoverable error occurs. */ public HttpServletRequest handleMultipartRequest(RequestWrapper request, ServletContext servletContext) throws HdivMultipartException { DiskFileUpload upload = new DiskFileUpload(); upload.setHeaderEncoding(request.getCharacterEncoding()); // Set the maximum size before a FileUploadException will be thrown. upload.setSizeMax(getSizeMax()); // Set the maximum size that will be stored in memory. upload.setSizeThreshold((int) getSizeThreshold()); // Set the the location for saving data on disk. upload.setRepositoryPath(getRepositoryPath(servletContext)); List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (DiskFileUpload.SizeLimitExceededException e) { if (log.isErrorEnabled()) { log.error("Size limit exceeded exception"); } // Special handling for uploads that are too big. throw new HdivMultipartException(e); } catch (FileUploadException e) { if (log.isErrorEnabled()) { log.error("Failed to parse multipart request", e); } throw new HdivMultipartException(e); } // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { this.addTextParameter(request, item); } else { this.addFileParameter(request, item); } } return request; }
From source file:org.jbpm.web.ProcessUploadServlet.java
private String handleRequest(HttpServletRequest request) { //check if request is multipart content log.debug("Handling upload request"); if (!FileUpload.isMultipartContent(request)) { log.debug("Not a multipart request"); return "Not a multipart request"; }/*from w w w . ja v a 2 s.co m*/ try { DiskFileUpload fileUpload = new DiskFileUpload(); List list = fileUpload.parseRequest(request); log.debug("Upload from GPD"); Iterator iterator = list.iterator(); if (!iterator.hasNext()) { log.debug("No process file in the request"); return "No process file in the request"; } FileItem fileItem = (FileItem) iterator.next(); if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) { log.debug("Not a process archive"); return "Not a process archive"; } try { log.debug("Deploying process archive " + fileItem.getName()); ZipInputStream zipInputStream = new ZipInputStream(fileItem.getInputStream()); JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext(); log.debug("Preparing to parse process archive"); ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream); log.debug("Created a processdefinition : " + processDefinition.getName()); jbpmContext.deployProcessDefinition(processDefinition); zipInputStream.close(); return "Deployed archive " + processDefinition.getName() + " successfully"; } catch (IOException e) { log.debug("Failed to read process archive", e); return "IOException"; } } catch (FileUploadException e) { log.debug("Failed to parse HTTP request", e); return "FileUploadException"; } }
From source file:org.junitee.testngee.servlet.TestNGEEServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DiskFileUpload upload = new DiskFileUpload(); List<File> xmlFiles = new ArrayList<File>(); try {//w w w . j a v a2 s . c om List items = upload.parseRequest(request); for (Iterator iterator = items.iterator(); iterator.hasNext();) { FileItem item = (FileItem) iterator.next(); if (item.isFormField()) { } else { // it's an uploaded xml file File file = File.createTempFile("testng", ".xml"); item.write(file); xmlFiles.add(file); } } File outdir = File.createTempFile("output", ""); outdir.delete(); outdir.mkdirs(); String[] args = new String[xmlFiles.size() + 2]; args[0] = "-d"; args[1] = outdir.getAbsolutePath(); int i = 2; for (Iterator<File> iterator = xmlFiles.iterator(); iterator.hasNext();) { File file = iterator.next(); args[i++] = file.getAbsolutePath(); } TestNG testNG = TestNG.privateMain(args, null); zipOutputDir(outdir, response.getOutputStream()); cleanup(xmlFiles, outdir); } catch (FileUploadException e) { throw new ServletException(e); } catch (Exception e) { throw new ServletException(e); } }
From source file:org.liquidsite.core.web.MultiPartRequest.java
/** * Parses the incoming multi-part HTTP request. * * @param request the HTTP request * * @throws FileUploadException if the request couldn't be parsed * correctly/*from w w w. ja v a 2 s . c om*/ */ private void parse(HttpServletRequest request) throws FileUploadException { DiskFileUpload parser = new DiskFileUpload(); List list; FileItem item; String value; // Create multi-part parser parser.setRepositoryPath(uploadDir); parser.setSizeMax(uploadSize); parser.setSizeThreshold(4096); // Parse request list = parser.parseRequest(request); for (int i = 0; i < list.size(); i++) { item = (FileItem) list.get(i); if (item.isFormField()) { try { value = item.getString("UTF-8"); } catch (UnsupportedEncodingException ignore) { value = item.getString(); } parameters.put(item.getFieldName(), value); } else { files.put(item.getFieldName(), new MultiPartFile(item)); } } }