List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator
public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException
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 {/*from w ww. j av a 2 s . c o 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:hudson.gwtmarketplace.server.ImageUploadServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); ServletFileUpload upload = new ServletFileUpload(); Map<String, String> parameters = new HashMap<String, String>(); Image resizedImage = null;/*from w ww .j a v a 2 s . c o m*/ try { // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { parameters.put(name, toString(stream)); } else { resizedImage = resize(stream); } } } catch (Exception e) { response.sendError(500); } String productId = parameters.get("key"); if (null != productId && null != resizedImage) { try { String iconKey = productMgr.setImageData(Long.parseLong(productId), resizedImage.getImageData()); if (null != iconKey) { response.getOutputStream().write(iconKey.getBytes()); } } catch (InvalidAccessException e) { e.printStackTrace(); } } }
From source file:com.sifiso.dvs.util.PhotoUtil.java
public ResponseDTO downloadPhotos(HttpServletRequest request, PlatformUtil platformUtil) throws FileUploadException { logger.log(Level.INFO, "######### starting PHOTO DOWNLOAD process\n\n"); ResponseDTO resp = new ResponseDTO(); InputStream stream = null;/* ww w .j a va2s. c o m*/ File rootDir; try { rootDir = dvsProperties.getImageDir(); logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath()); if (!rootDir.exists()) { rootDir.mkdir(); } } catch (Exception ex) { logger.log(Level.SEVERE, "Properties file problem", ex); resp.setMessage("Server file unavailable. Please try later"); resp.setStatusCode(114); return resp; } PhotoUploadDTO dto = null; Gson gson = new Gson(); File doctorFileDir = null, surgeryDir = null; try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); stream = item.openStream(); if (item.isFormField()) { if (name.equalsIgnoreCase("JSON")) { String json = Streams.asString(stream); if (json != null) { logger.log(Level.INFO, "picture with associated json: {0}", json); dto = gson.fromJson(json, PhotoUploadDTO.class); if (dto != null) { surgeryDir = createSurgeryFileDirectory(rootDir, surgeryDir, dto.getSurgeryID()); if (dto.getDoctorID() > 0) { doctorFileDir = createDoctorDirectory(surgeryDir, doctorFileDir, dto.getDoctorID()); } } } else { logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL.."); } } } else { File imageFile = null; if (dto == null) { continue; } DateTime dt = new DateTime(); String fileName = ""; if (dto.isIsFullPicture()) { fileName = "f" + dt.getMillis() + ".jpg"; } else { fileName = "t" + dt.getMillis() + ".jpg"; } if (dto.getPatientfileID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getPatientfileID() + ".jpg"; } else { fileName = "t" + dto.getPatientfileID() + ".jpg"; } } // switch (dto.getPictureType()) { case PhotoUploadDTO.FILES_DOCTOR: imageFile = new File(doctorFileDir, fileName); break; case PhotoUploadDTO.FILES_SURGERY: imageFile = new File(surgeryDir, fileName); } writeFile(stream, imageFile); resp.setStatusCode(0); resp.setMessage("Photo downloaded from mobile app "); //add database System.out.println("filepath: " + imageFile.getAbsolutePath()); //create uri /*int index = imageFile.getAbsolutePath().indexOf("monitor_images"); if (index > -1) { String uri = imageFile.getAbsolutePath().substring(index); System.out.println("uri: " + uri); dto.setUri(uri); } dto.setDateUploaded(new Date()); if (dto.isIsFullPicture()) { dto.setThumbFlag(null); } else { dto.setThumbFlag(1); } dataUtil.addPhotoUpload(dto);*/ } } } catch (FileUploadException | IOException | JsonSyntaxException ex) { logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex); throw new FileUploadException(); } return resp; }
From source file:freedots.web.MusicXML2BrailleServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Score score = null;/*w w w . j a v a 2 s. c o m*/ BrailleEncoding brailleEncoding = BrailleEncoding.UnicodeBraille; int width = 40, height = 25; InputStream stream = null; ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { final FileItemStream item = iterator.next(); if (item.getFieldName().compareTo("file.xml") == 0) { String extension = "xml"; if (item.getName().endsWith(".mxl")) extension = "mxl"; score = parseMusicXML(item.openStream(), extension); } else if (item.getFieldName().compareTo("encoding") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null) { try { brailleEncoding = Enum.valueOf(BrailleEncoding.class, line); } catch (IllegalArgumentException e) { LOG.info("Unknown encoding " + line + ", falling back to default"); } } } else if (item.getFieldName().compareTo("width") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null && !line.isEmpty()) { try { final int value = Integer.parseInt(line); if (value >= MIN_COLUMNS_PER_LINE && value <= MAX_COLUMNS_PER_LINE) width = value; } catch (NumberFormatException e) { LOG.info("Not a proper number: " + line + ", falling back to default"); } } } else if (item.getFieldName().compareTo("height") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null && !line.isEmpty()) { try { final int value = Integer.parseInt(line); if (value >= MIN_LINES_PER_PAGE && value <= MAX_LINES_PER_PAGE) height = value; } catch (NumberFormatException e) { LOG.info("Not a proper number: " + line + ", falling back to default"); } } } } } catch (org.apache.commons.fileupload.FileUploadException e) { LOG.info("FileUploadException error"); resp.sendError(500); } if (score != null) { writeResult(score, width, height, Method.SectionBySection, brailleEncoding, resp); } else { resp.sendRedirect("/"); } }
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 w ww . ja v a 2 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.pronoiahealth.olhie.server.rest.BooklogoUploadServiceImpl.java
@Override @POST//from w ww.ja va2s . co m @Path("/upload") @Produces("text/html") @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR }) public String process(@Context HttpServletRequest req) throws ServletException, IOException, FileUploadException { try { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart == true) { // FileItemFactory fileItemFactory = new FileItemFactory(); String bookId = null; String contentType = null; // String data = null; byte[] bytes = null; String fileName = null; long size = 0; ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setSizeMax(FILE_SIZE_LIMIT); FileItemIterator iter = fileUpload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // BookId if (item.getFieldName().equals("bookId")) { bookId = Streams.asString(stream); } } else { if (item != null) { contentType = item.getContentType(); fileName = item.getName(); item.openStream(); InputStream in = item.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(in, bos); bytes = bos.toByteArray(); // fileItem.get(); size = bytes.length; // data = Base64.encodeBytes(bytes); } } } // Add the logo Book book = bookDAO.getBookById(bookId); // Update the front cover BookCategory cat = holder.getCategoryByName(book.getCategory()); BookCover cover = holder.getCoverByName(book.getCoverName()); String authorName = bookDAO.getAuthorName(book.getAuthorId()); //String frontBookCoverEncoded = imgService // .createDefaultFrontCoverEncoded(book, cat, cover, // bytes, authorName); byte[] frontBookCoverBytes = imgService.createDefaultFrontCover(book, cat, cover, bytes, authorName); //String smallFrontBookCoverEncoded = imgService // .createDefaultSmallFrontCoverEncoded(book, cat, cover, // bytes, authorName); byte[] frontBookCoverSmallBytes = imgService.createDefaultSmallFrontCover(book, cat, cover, bytes, authorName); // Save it // Add the logo book = bookDAO.addLogoAndFrontCoverBytes(bookId, contentType, bytes, fileName, size, frontBookCoverBytes, frontBookCoverSmallBytes); } return "OK"; } catch (Exception e) { log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e); // return "ERROR:\n" + e.getMessage(); if (e instanceof FileUploadException) { throw (FileUploadException) e; } else { throw new FileUploadException(e.getMessage()); } } }
From source file:edu.isi.wings.portal.servlets.HandleUpload.java
/** * Handle an HTTP POST request from Plupload. *//*from www . j av a 2 s .co m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Config config = new Config(request); if (!config.checkDomain(request, response)) return; Domain dom = config.getDomain(); String name = null; String id = null; String storageDir = dom.getDomainDirectory() + "/"; int chunk = 0; int chunks = 0; boolean isComponent = false; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); try { InputStream input = item.openStream(); if (item.isFormField()) { String fieldName = item.getFieldName(); String value = Streams.asString(input); if ("name".equals(fieldName)) name = value.replaceAll("[^\\w\\.\\-_]+", "_"); else if ("id".equals(fieldName)) id = value; else if ("type".equals(fieldName)) { if ("data".equals(value)) storageDir += dom.getDataLibrary().getStorageDirectory(); else if ("component".equals(value)) { storageDir += dom.getConcreteComponentLibrary().getStorageDirectory(); isComponent = true; } else { storageDir = System.getProperty("java.io.tmpdir"); } } else if ("chunk".equals(fieldName)) chunk = Integer.parseInt(value); else if ("chunks".equals(fieldName)) chunks = Integer.parseInt(value); } else if (name != null) { File storageDirFile = new File(storageDir); if (!storageDirFile.exists()) storageDirFile.mkdirs(); File uploadFile = new File(storageDirFile.getPath() + "/" + name + ".part"); saveUploadFile(input, uploadFile, chunk); } } catch (Exception e) { this.printError(out, e.getMessage()); e.printStackTrace(); } } } catch (FileUploadException e1) { this.printError(out, e1.getMessage()); e1.printStackTrace(); } } else { this.printError(out, "Not multipart data"); } if (chunks == 0 || chunk == chunks - 1) { // Done upload File partUpload = new File(storageDir + File.separator + name + ".part"); File finalUpload = new File(storageDir + File.separator + name); partUpload.renameTo(finalUpload); String mime = new Tika().detect(finalUpload); if (mime.equals("application/x-sh") || mime.startsWith("text/")) FileUtils.writeLines(finalUpload, FileUtils.readLines(finalUpload)); // Check if this is a zip file and unzip if needed String location = finalUpload.getAbsolutePath(); if (isComponent && mime.equals("application/zip")) { String dirname = new URI(id).getFragment(); location = StorageHandler.unzipFile(finalUpload, dirname, storageDir); finalUpload.delete(); } this.printOk(out, location); } }
From source file:com.chinarewards.gwt.license.util.FileUploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // text/html IE?? response.setContentType("text/plain;charset=utf-8"); StringBuffer responseMessage = new StringBuffer("<?xml version=\"1.0\" encoding=\"GB2312\"?>"); responseMessage.append("<root>"); StringBuffer errorMsg = new StringBuffer(responseMessage).append("<result>").append("FAILED") .append("</result>"); String info = ""; ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = null;// w w w . ja v a 2 s.c o m try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { info = "Form field " + name + " with value " + Streams.asString(stream) + " detected."; responseMessage = new StringBuffer(responseMessage).append(errorMsg).append("<info>") .append(info).append("</info>"); finishPrintResponseMsg(response, responseMessage); return; } else { BufferedInputStream inputStream = new BufferedInputStream(stream);// ? String uploadPath = getUploadPath(request, "upload"); if (uploadPath != null) { String fileName = getOutputFileName(item); String outputFilePath = getOutputFilePath(uploadPath, fileName); int widthdist = 72; int heightdist = 72; widthdist = 200; heightdist = 200; BufferedOutputStream outputStream = new BufferedOutputStream( new FileOutputStream(new File(outputFilePath)));// ? Streams.copy(inputStream, outputStream, true); // // stream.close(); reduceImg(inputStream, outputFilePath, outputFilePath, widthdist, heightdist, 0); stream.close(); responseMessage.append("<result>").append("SUCCESS").append("</result>"); responseMessage.append("<info>"); responseMessage.append(fileName); responseMessage.append(info).append("</info>"); } else { responseMessage = errorMsg.append("<info>").append("") .append("</info>"); } } } } catch (Exception e) { e.printStackTrace(); responseMessage = errorMsg.append("<info>").append(":" + e.getMessage()) .append("</info>"); } finishPrintResponseMsg(response, responseMessage); }
From source file:de.mpg.imeji.presentation.upload.UploadBean.java
public void upload() throws Exception { HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();/* w ww .j av a 2 s .c o m*/ boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { title = item.getName(); StringTokenizer st = new StringTokenizer(title, "."); while (st.hasMoreTokens()) { format = st.nextToken(); } mimetype = "image/" + format; // TODO remove static image description description = ""; try { UserController uc = new UserController(null); User user = uc.retrieve(getUser().getEmail()); try { DepositController controller = new DepositController(); Item escidocItem = controller.createEscidocItem(stream, title, mimetype, format); controller.createImejiImage(collection, user, escidocItem.getOriginObjid(), title, URI.create(EscidocHelper.getOriginalResolution(escidocItem)), URI.create(EscidocHelper.getThumbnailUrl(escidocItem)), URI.create(EscidocHelper.getWebResolutionUrl(escidocItem))); // controller.createImejiImage(collection, user, "escidoc:123", title, // URI.create("http://imeji.org/test"), URI.create("http://imeji.org/test"), // URI.create("http://imeji.org/test")); sNum += 1; sFiles.add(title); } catch (Exception e) { fNum += 1; fFiles.add(title); logger.error("Error uploading image: ", e); // throw new RuntimeException(e); } } catch (Exception e) { throw new RuntimeException(e); } } } logger.info("Upload finished"); } }
From source file:com.doculibre.constellio.feedprotocol.FeedServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.fine("FeedServlet: doPost(...)"); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); PrintWriter out = null;/*w w w. jav a 2 s . c o m*/ try { out = response.getWriter(); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); String datasource = null; String feedtype = null; FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); //Disabled to allow easier update from HTML forms //if (item.isFormField()) { if (item.getFieldName().equals(FeedParser.XML_DATASOURCE)) { InputStream itemStream = null; try { itemStream = item.openStream(); datasource = IOUtils.toString(itemStream); } finally { IOUtils.closeQuietly(itemStream); } } else if (item.getFieldName().equals(FeedParser.XML_FEEDTYPE)) { InputStream itemStream = null; try { itemStream = item.openStream(); feedtype = IOUtils.toString(itemStream); } finally { IOUtils.closeQuietly(itemStream); } } else if (item.getFieldName().equals(FeedParser.XML_DATA)) { try { if (StringUtils.isBlank(datasource)) { throw new IllegalArgumentException("Datasource is blank"); } if (StringUtils.isBlank(feedtype)) { throw new IllegalArgumentException("Feedtype is blank"); } InputStream contentStream = null; try { contentStream = item.openStream(); final Feed feed = new FeedStaxParser().parse(datasource, feedtype, contentStream); Callable<Object> processFeedTask = new Callable<Object>() { @Override public Object call() throws Exception { FeedProcessor feedProcessor = new FeedProcessor(feed); feedProcessor.processFeed(); return null; } }; threadPoolExecutor.submit(processFeedTask); out.append(GsaFeedConnection.SUCCESS_RESPONSE); return; } catch (Exception e) { LOG.log(Level.SEVERE, "Exception while processing contentStream", e); } finally { IOUtils.closeQuietly(contentStream); } } finally { IOUtils.closeQuietly(out); } } //} } } } catch (Throwable e) { LOG.log(Level.SEVERE, "Exception while uploading", e); } finally { IOUtils.closeQuietly(out); } out.append(GsaFeedConnection.INTERNAL_ERROR_RESPONSE); }