List of usage examples for org.apache.commons.fileupload FileItemStream openStream
InputStream openStream() throws IOException;
From source file:de.mpg.imeji.presentation.upload.UploadBean.java
public void upload() throws Exception { HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();/*w w w. j a v a 2 s . co 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:fedora.server.management.UploadServlet.java
/** * The servlet entry point. http://host:port/fedora/management/upload *//*from www. j a v a 2 s . c o m*/ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Context context = ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri, request); try { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request, looking for "file" InputStream in = null; FileItemIterator iter = upload.getItemIterator(request); while (in == null && iter.hasNext()) { FileItemStream item = iter.next(); LOG.info("Got next item: isFormField=" + item.isFormField() + " fieldName=" + item.getFieldName()); if (!item.isFormField() && item.getFieldName().equals("file")) { in = item.openStream(); } } if (in == null) { sendResponse(HttpServletResponse.SC_BAD_REQUEST, "No data sent.", response); } else { sendResponse(HttpServletResponse.SC_CREATED, s_management.putTempStream(context, in), response); } } catch (AuthzException ae) { throw RootException.getServletException(ae, request, "Upload", new String[0]); } catch (Exception e) { e.printStackTrace(); sendResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getClass().getName() + ": " + e.getMessage(), response); } }
From source file:com.google.reducisaurus.servlets.BaseServlet.java
private String collectFromFileUpload(final HttpServletRequest req) throws IOException, ServletException { StringBuilder collector = new StringBuilder(); try {//from ww w .ja v a2s .c o m ServletFileUpload sfu = new ServletFileUpload(); FileItemIterator it = sfu.getItemIterator(req); while (it.hasNext()) { FileItemStream item = it.next(); if (!item.isFormField()) { InputStream stream = item.openStream(); collector.append(IOUtils.toString(stream, "UTF-8")); collector.append("\n"); IOUtils.closeQuietly(stream); } } } catch (FileUploadException e) { throw new ServletException(e); } return collector.toString(); }
From source file:com.fullmetalgalaxy.server.pm.PMServlet.java
@Override protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); try {//w w w.j a v a 2 s .c o m // build message to send Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(session); msg.setSubject("[FMG] no subject", "text/plain"); msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin")); msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin")); EbAccount fromAccount = null; // Parse the request FileItemIterator iter = upload.getItemIterator(p_request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { if ("msg".equalsIgnoreCase(item.getFieldName())) { msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain"); } if ("subject".equalsIgnoreCase(item.getFieldName())) { msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain"); } if ("toid".equalsIgnoreCase(item.getFieldName())) { EbAccount account = null; try { account = FmgDataStore.dao().get(EbAccount.class, Long.parseLong(Streams.asString(item.openStream(), "UTF-8"))); } catch (NumberFormatException e) { } if (account != null) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(account.getEmail(), account.getPseudo())); } } if ("fromid".equalsIgnoreCase(item.getFieldName())) { try { fromAccount = FmgDataStore.dao().get(EbAccount.class, Long.parseLong(Streams.asString(item.openStream(), "UTF-8"))); } catch (NumberFormatException e) { } if (fromAccount != null) { if (fromAccount.getAuthProvider() == AuthProvider.Google && !fromAccount.isHideEmailToPlayer()) { msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo())); } else { msg.setFrom( new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo())); } } } } } // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse( // "archive@fullmetalgalaxy.com" ) ); Transport.send(msg); } catch (Exception e) { log.error(e); p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage()); return; } p_response.sendRedirect("/genericmsg.jsp?title=Message envoye"); }
From source file:com.vmware.photon.controller.api.frontend.resources.vm.VmIsoAttachResource.java
private Task parseIsoDataFromRequest(HttpServletRequest request, String id) throws InternalException, ExternalException { Task task = null;/* ww w .ja v a2 s.c o m*/ ServletFileUpload fileUpload = new ServletFileUpload(); List<InputStream> dataStreams = new LinkedList<>(); try { FileItemIterator iterator = fileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { logger.warn(String.format("The parameter '%s' is unknown in attach ISO.", item.getFieldName())); } else { InputStream fileStream = item.openStream(); dataStreams.add(fileStream); task = vmFeClient.attachIso(id, fileStream, item.getName()); } } } catch (IOException ex) { throw new IsoUploadException("Iso upload IOException", ex); } catch (FileUploadException ex) { throw new IsoUploadException("Iso upload FileUploadException", ex); } finally { for (InputStream stream : dataStreams) { try { stream.close(); } catch (IOException | NullPointerException ex) { logger.warn("Unexpected exception closing data stream.", ex); } } } if (task == null) { throw new IsoUploadException("There is no iso stream data in the iso upload request."); } return task; }
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 w w . j a v a 2s.c om 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 . jav a 2 s.co 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:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java
private void parseReq(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { try {/*from ww w . j a va2 s .c o m*/ MF mf = MF.getFactory(); req.setCharacterEncoding("UTF-8"); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); HashMap<String, String> map = new HashMap<String, String>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { String field = item.getFieldName(); String value = Streams.asString(stream); map.put(field, value); stream.close(); } else { String filename = item.getName(); String[] extension = filename.split("\\."); String mail = map.get("mail"); if (mail != null) { filename = mail + "_" + String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } else { filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } map.put("filename", filename); byte[] buffer = IOUtils.toByteArray(stream); mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer, filename); stream.close(); } } String email = map.get("mail"); String firstName = map.get("firstName"); String lastName = map.get("lastName"); String dayS = map.get("day"); String monthS = map.get("month"); String yearS = map.get("year"); String password = map.get("password"); String filename = map.get("filename"); String date = yearS + "-" + monthS + "-" + dayS; char gender = map.get("gender").charAt(0); RequestDispatcher disp; Connection c = mf.getSQLService().getConnection(); String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')"; Statement statement = c.createStatement(); statement.executeUpdate(stm); statement.close(); c.close(); req.getSession(true).setAttribute("actualUser", email); req.getSession(true).setAttribute("edit", "false"); disp = req.getRequestDispatcher("SelectTopic.jsp"); disp.forward(req, response); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileUploadException e) { e.printStackTrace(); } }
From source file:act.util.UploadFileStorageService.java
private ISObject _store(FileItemStream fileItemStream) throws IOException { String filename = fileItemStream.getName(); String key = newKey(filename); File tmpFile = getFile(key);/* www. ja v a 2 s . c om*/ InputStream input = fileItemStream.openStream(); ThresholdingByteArrayOutputStream output = new ThresholdingByteArrayOutputStream(inMemoryCacheThreshold, tmpFile); IO.copy(input, output); ISObject retVal; if (output.exceedThreshold) { retVal = getFull(key); } else { int size = output.written; byte[] buf = output.buf(); retVal = SObject.of(key, buf, size); } if (S.notBlank(filename)) { retVal.setFilename(filename); } String contentType = fileItemStream.getContentType(); if (null != contentType) { retVal.setContentType(contentType); } return retVal; }
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 w w w. 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); // 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()); } }