List of usage examples for org.apache.commons.fileupload FileItemIterator next
FileItemStream next() throws FileUploadException, IOException;
From source file:com.smartgwt.extensions.fileuploader.server.ProjectServlet.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); boolean isGWT = true; try {//from www .ja v a 2s . co m if (log.isDebugEnabled()) log.debug(request.getParameterMap()); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); // pick up parameters first and note actual FileItem while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { args.put(name, Streams.asString(item.openStream())); } else { args.put("contentType", item.getContentType()); String fileName = item.getName(); int slash = fileName.lastIndexOf("/"); if (slash < 0) slash = fileName.lastIndexOf("\\"); if (slash > 0) fileName = fileName.substring(slash + 1); args.put("fileName", fileName); // upload requests can come from smartGWT (args) or // FCKEditor (request) String contextName = args.get("context"); String model = args.get("model"); String path = args.get("path"); if (contextName == null) { isGWT = false; contextName = request.getParameter("context"); model = request.getParameter("model"); path = request.getParameter("path"); if (log.isDebugEnabled()) log.debug("query=" + request.getQueryString()); } else if (log.isDebugEnabled()) log.debug(args); // the following code stores the file based on your parameters /* ProjectContext context = ContextService.get().getContext( contextName); ProjectState state = (ProjectState) request.getSession() .getAttribute(contextName); InputStream in = null; try { in = item.openStream(); state.getFileManager().storeFile( context.getModel(model), path + fileName, in); } catch (Exception e) { e.printStackTrace(); log.error("Fail to upload " + fileName + " to " + path); } finally { if (in != null) try { in.close(); } catch (Exception e) { } } */ } } // TODO: need to handle conversion options and error reporting response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); if (isGWT) { out.println("<script type=\"text/javascript\">"); out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); } else out.println(getEditorResponse()); out.println("</body>"); out.println("</html>"); out.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.google.phonenumbers.PhoneNumberParserServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String phoneNumber = null;/*from www .j a v a 2 s. c om*/ String defaultCountry = null; String languageCode = "en"; // Default languageCode to English if nothing is entered. String regionCode = ""; String fileContents = null; ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(50000); try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName.equals("phoneNumber")) { phoneNumber = Streams.asString(in, "UTF-8"); } else if (fieldName.equals("defaultCountry")) { defaultCountry = Streams.asString(in).toUpperCase(); } else if (fieldName.equals("languageCode")) { String languageEntered = Streams.asString(in).toLowerCase(); if (languageEntered.length() > 0) { languageCode = languageEntered; } } else if (fieldName.equals("regionCode")) { regionCode = Streams.asString(in).toUpperCase(); } } else { try { fileContents = IOUtils.toString(in); } finally { IOUtils.closeQuietly(in); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } StringBuilder output; if (fileContents.length() == 0) { output = getOutputForSingleNumber(phoneNumber, defaultCountry, languageCode, regionCode); resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().println("<html><head>"); resp.getWriter() .println("<link type=\"text/css\" rel=\"stylesheet\" href=\"/stylesheets/main.css\" />"); resp.getWriter().println("</head>"); resp.getWriter().println("<body>"); resp.getWriter().println("Phone Number entered: " + phoneNumber + "<br>"); resp.getWriter().println("defaultCountry entered: " + defaultCountry + "<br>"); resp.getWriter().println("Language entered: " + languageCode + (regionCode.length() == 0 ? "" : " (" + regionCode + ")" + "<br>")); } else { output = getOutputForFile(defaultCountry, fileContents); resp.setContentType("text/html"); } resp.getWriter().println(output); resp.getWriter().println("</body></html>"); }
From source file:com.glaf.core.web.servlet.FileUploadServlet.java
public void upload(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html;charset=UTF-8"); LoginContext loginContext = RequestUtils.getLoginContext(request); if (loginContext == null) { return;//from w w w. j ava2s . c om } String serviceKey = request.getParameter("serviceKey"); String type = request.getParameter("type"); if (StringUtils.isEmpty(type)) { type = "0"; } Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap:" + paramMap); String rootDir = SystemProperties.getConfigRootPath(); InputStream inputStream = null; try { DiskFileItemFactory diskFactory = new DiskFileItemFactory(); // threshold ???? 8M diskFactory.setSizeThreshold(8 * FileUtils.MB_SIZE); // repository diskFactory.setRepository(new File(rootDir + "/temp")); ServletFileUpload upload = new ServletFileUpload(diskFactory); int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0); if (maxUploadSize == 0) { maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB } maxUploadSize = maxUploadSize * FileUtils.MB_SIZE; logger.debug("maxUploadSize:" + maxUploadSize); upload.setHeaderEncoding("UTF-8"); upload.setSizeMax(maxUploadSize); upload.setFileSizeMax(maxUploadSize); String uploadDir = Constants.UPLOAD_PATH; if (ServletFileUpload.isMultipartContent(request)) { logger.debug("#################start upload process#########################"); FileItemIterator iter = upload.getItemIterator(request); PrintWriter out = response.getWriter(); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { // ???? String autoCreatedDateDirByParttern = "yyyy/MM/dd"; String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(), autoCreatedDateDirByParttern); File savePath = new File(rootDir + uploadDir + autoCreatedDateDir); if (!savePath.exists()) { savePath.mkdirs(); } String fileId = UUID32.getUUID(); String fileName = savePath + "/" + fileId; BlobItem dataFile = new BlobItemEntity(); dataFile.setLastModified(System.currentTimeMillis()); dataFile.setCreateBy(loginContext.getActorId()); dataFile.setFileId(fileId); dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId); dataFile.setFilename(item.getName()); dataFile.setName(item.getName()); dataFile.setContentType(item.getContentType()); dataFile.setType(type); dataFile.setStatus(0); dataFile.setServiceKey(serviceKey); getBlobService().insertBlob(dataFile); inputStream = item.openStream(); FileUtils.save(fileName, inputStream); logger.debug(fileName + " save ok."); out.print(fileId); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { IOUtils.close(inputStream); } }
From source file:jhi.buntata.server.NodeMedia.java
@Put public boolean putMedia(Representation entity) { if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { try {//w w w .j av a 2s .c o m BuntataNode node = nodeDAO.get(id); DiskFileItemFactory factory = new DiskFileItemFactory(); RestletFileUpload upload = new RestletFileUpload(factory); FileItemIterator fileIterator = upload.getItemIterator(entity); if (fileIterator.hasNext()) { String nodeName = node.getName().replace(" ", "-"); File dir = new File(dataDir, nodeName); dir.mkdirs(); FileItemStream fi = fileIterator.next(); String name = fi.getName(); File file = new File(dir, name); int i = 1; while (file.exists()) file = new File(dir, (i++) + name); // Copy the file to its target location Files.copy(fi.openStream(), file.toPath()); // Create the media entity String relativePath = new File(dataDir).toURI().relativize(file.toURI()).getPath(); BuntataMedia media = new BuntataMedia(null, new Date(), new Date()) .setInternalLink(relativePath).setName(name).setDescription(name).setMediaTypeId(1L); mediaDAO.add(media); // Create the node media entity nodeMediaDAO.add(new BuntataNodeMedia().setMediaId(media.getId()).setNodeId(node.getId())); return true; } } catch (Exception e) { e.printStackTrace(); } } else { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE); } return false; }
From source file:graphql.servlet.GraphQLServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { GraphQLContext context = createContext(Optional.of(req), Optional.of(resp)); InputStream inputStream = null; if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload upload = new ServletFileUpload(); try {/*from ww w . j a va2 s . co m*/ FileItemIterator it = upload.getItemIterator(req); context.setFiles(Optional.of(it)); while (inputStream == null && it.hasNext()) { FileItemStream stream = it.next(); if (stream.getFieldName().contentEquals("graphql")) { inputStream = stream.openStream(); } } if (inputStream == null) { throw new ServletException("no query found"); } } catch (FileUploadException e) { throw new ServletException("no query found"); } } else { // this is not a multipart request inputStream = req.getInputStream(); } Request request = new ObjectMapper().readValue(inputStream, Request.class); Map<String, Object> variables = request.variables; if (variables == null) { variables = new HashMap<>(); } query(request.query, request.operationName, variables, getSchema(), req, resp, context); }
From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); try {//from w ww . j av a2 s . c o m ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); FileItemStream fileItem = null; // pick up parameters first and note actual FileItem while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { args.put(name, Streams.asString(item.openStream())); } else { fileItem = item; } } if (fileItem != null) { args.put("contentType", fileItem.getContentType()); args.put("fileName", FileUtils.filename(fileItem.getName())); System.out.println("uploading args " + args); String context = args.get("context"); String model = args.get("model"); String xq = args.get("xq"); System.out.println(context + "," + model + "," + xq); File f = new File(args.get("fileName")); System.out.println(f.getAbsolutePath()); /* * TODO: pboysen get the state, context and fileManager and store the * stream in fileName. Parameters should be passed to locate state * and conversion options. */ response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script>"); out.println("top.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); } else { //TODO: add error code } } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.priocept.jcr.server.UploadServlet.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); try {// w w w . j a v a 2 s . co m if (log.isDebugEnabled()) log.debug(request.getParameterMap()); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); // pick up parameters first and note actual FileItem while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { args.put(name, Streams.asString(item.openStream())); } else { args.put("contentType", item.getContentType()); String fileName = item.getName(); int slash = fileName.lastIndexOf("/"); if (slash < 0) slash = fileName.lastIndexOf("\\"); if (slash > 0) fileName = fileName.substring(slash + 1); args.put("fileName", fileName); if (log.isDebugEnabled()) log.debug(args); InputStream in = null; try { in = item.openStream(); writeToFile(request.getSession().getId() + "/" + fileName, in, true, request.getSession().getServletContext().getRealPath("/")); } catch (Exception e) { // e.printStackTrace(); log.error("Fail to upload " + fileName); response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script type=\"text/javascript\">"); out.println("if (parent.uploadFailed) parent.uploadFailed('" + e.getLocalizedMessage().replaceAll("\'|\"", "") + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); return; } finally { if (in != null) try { in.close(); } catch (Exception e) { } } } } response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script type=\"text/javascript\">"); out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.newatlanta.appengine.servlet.GaeVfsServlet.java
/** * Writes the uploaded file to the GAE virtual file system (GaeVFS). Copied from: * /* ww w .j a va 2s . c o m*/ * http://code.google.com/appengine/kb/java.html#fileforms * * The "path" form parameter specifies a <a href="http://code.google.com/p/gaevfs/wiki/CombinedLocalOption" * target="_blank">GaeVFS path</a>. All directories within the path hierarchy * are created (if they don't already exist) when the file is saved. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Check that we have a file upload request if (!ServletFileUpload.isMultipartContent(req)) { res.sendError(SC_BAD_REQUEST, "form enctype not multipart/form-data"); } try { String path = "/"; int blockSize = 0; ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("path")) { path = asString(item.openStream()); if (!path.endsWith("/")) { path = path + "/"; } } else if (item.getFieldName().equalsIgnoreCase("blocksize")) { String s = asString(item.openStream()); if (s.length() > 0) { blockSize = Integer.parseInt(s); } } } else { Path filePath = Paths.get(path + item.getName()); Path parent = filePath.getParent(); if (parent.notExists()) { createDirectories(parent); } if (blockSize > 0) { filePath.createFile(withBlockSize(blockSize)); } else { filePath.createFile(); } // IOUtils.copy() buffers the InputStream internally OutputStream out = new BufferedOutputStream(filePath.newOutputStream(), BUFF_SIZE); copy(item.openStream(), out); out.close(); } } // redirect to the configured response, or to this servlet for a // directory listing res.sendRedirect(uploadRedirect != null ? uploadRedirect : path); } catch (FileUploadException e) { throw new ServletException(e); } }
From source file:com.manydesigns.portofino.stripes.StreamingCommonsMultipartWrapper.java
/** * Pseudo-constructor that allows the class to perform any initialization necessary. * * @param request an HttpServletRequest that has a content-type of multipart. * @param tempDir a File representing the temporary directory that can be used to store * file parts as they are uploaded if this is desirable * @param maxPostSize the size in bytes beyond which the request should not be read, and a * FileUploadLimitExceeded exception should be thrown * @throws IOException if a problem occurs processing the request of storing temporary * files/*from w ww . j ava 2 s .c o m*/ * @throws FileUploadLimitExceededException if the POST content is longer than the * maxPostSize supplied. */ @SuppressWarnings("unchecked") public void build(HttpServletRequest request, File tempDir, long maxPostSize) throws IOException, FileUploadLimitExceededException { try { this.charset = request.getCharacterEncoding(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); FileItemIterator iterator = upload.getItemIterator(request); Map<String, List<String>> params = new HashMap<String, List<String>>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); // If it's a form field, add the string value to the list if (item.isFormField()) { List<String> values = params.get(item.getFieldName()); if (values == null) { values = new ArrayList<String>(); params.put(item.getFieldName(), values); } values.add(charset == null ? IOUtils.toString(stream) : IOUtils.toString(stream, charset)); } // Else store the file param else { TempFile tempFile = TempFileService.getInstance().newTempFile(item.getContentType(), item.getName()); int size = IOUtils.copy(stream, tempFile.getOutputStream()); FileItem fileItem = new FileItem(item.getName(), item.getContentType(), tempFile, size); files.put(item.getFieldName(), fileItem); } } // Now convert them down into the usual map of String->String[] for (Map.Entry<String, List<String>> entry : params.entrySet()) { List<String> values = entry.getValue(); this.parameters.put(entry.getKey(), values.toArray(new String[values.size()])); } } catch (FileUploadBase.SizeLimitExceededException slee) { throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize()); } catch (FileUploadException fue) { IOException ioe = new IOException("Could not parse and cache file upload data."); ioe.initCause(fue); throw ioe; } }
From source file:com.vmware.photon.controller.api.frontend.resources.image.ImagesResource.java
private Task parseImageDataFromRequest(HttpServletRequest request) throws InternalException, ExternalException { Task task = null;/*from www . j ava 2 s. com*/ ServletFileUpload fileUpload = new ServletFileUpload(); FileItemIterator iterator = null; InputStream itemStream = null; try { ImageReplicationType replicationType = null; iterator = fileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); itemStream = item.openStream(); if (item.isFormField()) { String fieldName = item.getFieldName(); switch (fieldName.toUpperCase()) { case "IMAGEREPLICATION": replicationType = ImageReplicationType.valueOf(Streams.asString(itemStream).toUpperCase()); break; default: logger.warn(String.format("The parameter '%s' is unknown in image upload.", fieldName)); } } else { if (replicationType == null) { throw new ImageUploadException( "ImageReplicationType is required and should be encoded before image data in the upload request."); } task = imageFeClient.create(itemStream, item.getName(), replicationType); } itemStream.close(); itemStream = null; } } catch (IllegalArgumentException ex) { throw new ImageUploadException("Image upload receives invalid parameter", ex); } catch (IOException ex) { throw new ImageUploadException("Image upload IOException", ex); } catch (FileUploadException ex) { throw new ImageUploadException("Image upload FileUploadException", ex); } finally { flushRequest(iterator, itemStream); } if (task == null) { throw new ImageUploadException("There is no image stream data in the image upload request."); } return task; }