List of usage examples for org.apache.commons.fileupload FileItemStream getFieldName
String getFieldName();
From source file:foo.domaintest.http.HttpApiModuleTest.java
FileItemStream createItem(String name, String value, boolean isFormField) throws Exception { FileItemStream item = mock(FileItemStream.class); when(item.isFormField()).thenReturn(isFormField); when(isFormField ? item.getFieldName() : item.getName()).thenReturn(name); // Use UTF_16 and specify it to provideParameterMap to make sure we honor the request encoding. when(item.openStream()).thenReturn(new ByteArrayInputStream(value.getBytes(UTF_16))); return item;/*w w w .j a va 2 s . c o m*/ }
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.j av a2 s .com 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:com.twosigma.beaker.core.module.elfinder.ConnectorController.java
private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception { if (!ServletFileUpload.isMultipartContent(request)) return request; final Map<String, String> requestParams = new HashMap<String, String>(); List<FileItemStream> listFiles = new ArrayList<FileItemStream>(); // Parse the request ServletFileUpload sfu = new ServletFileUpload(); String characterEncoding = request.getCharacterEncoding(); if (characterEncoding == null) { characterEncoding = "UTF-8"; }//from w ww . j a v a 2s . c o m sfu.setHeaderEncoding(characterEncoding); FileItemIterator iter = sfu.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { requestParams.put(name, Streams.asString(stream, characterEncoding)); } else { String fileName = item.getName(); if (fileName != null && !"".equals(fileName.trim())) { ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); final byte[] bs = os.toByteArray(); stream.close(); listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { FileItemStream.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("openStream".equals(method.getName())) { return new ByteArrayInputStream(bs); } return method.invoke(item, args); } })); } } } request.setAttribute(FileItemStream.class.getName(), listFiles); Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { HttpServletRequest.class }, new InvocationHandler() { @Override public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable { // we replace getParameter() and getParameterValues() // methods if ("getParameter".equals(arg1.getName())) { String paramName = (String) arg2[0]; return requestParams.get(paramName); } if ("getParameterValues".equals(arg1.getName())) { String paramName = (String) arg2[0]; // normalize name 'key[]' to 'key' if (paramName.endsWith("[]")) paramName = paramName.substring(0, paramName.length() - 2); if (requestParams.containsKey(paramName)) return new String[] { requestParams.get(paramName) }; // if contains key[1], key[2]... int i = 0; List<String> paramValues = new ArrayList<String>(); while (true) { String name2 = String.format("%s[%d]", paramName, i++); if (requestParams.containsKey(name2)) { paramValues.add(requestParams.get(name2)); } else { break; } } return paramValues.isEmpty() ? new String[0] : paramValues.toArray(new String[paramValues.size()]); } return arg1.invoke(request, arg2); } }); return (HttpServletRequest) proxyInstance; }
From source file:de.egore911.reader.servlets.OpmlImportServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User user = getUserOrRedirect(resp); if (user == null) { return;/*from www .j a va2 s .c o m*/ } boolean success = false; String reason = null; ServletFileUpload upload = new ServletFileUpload(); CategoryDao categoryDao = new CategoryDao(); FeedUserDao feedUserDao = new FeedUserDao(); FeedDao feedDao = new FeedDao(); try { FileItemIterator iter = upload.getItemIterator(req); // Parse the request while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if ("subscriptions".equals(name) && !item.isFormField() && "text/xml".equals(item.getContentType())) { try (InputStream stream = item.openStream()) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(stream); document.getDocumentElement().normalize(); Element opml = document.getDocumentElement(); if (!"opml".equals(opml.getTagName())) { throw new ServletException("Invalid XML"); } NodeList nodes = opml.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; if ("body".equals(element.getTagName())) { if (countFeeds(element.getChildNodes()) < 20) { importRecursive(categoryDao, feedUserDao, feedDao, user, Category.ROOT, element.getChildNodes()); success = true; } else { reason = "to_many_feeds"; } } } } } catch (ParserConfigurationException | SAXException e) { throw new ServletException(e.getMessage(), e); } } } } catch (FileUploadException e) { throw new ServletException(e.getMessage(), e); } if (success) { resp.sendRedirect("/reader"); } else { String redirectTo = "/import?msg=import_failed"; if (reason != null) { redirectTo += "&reason=" + reason; } resp.sendRedirect(redirectTo); } }
From source file:controllers.PictureController.java
@FilterWith(SecureFilter.class) public Result uploadFinish(@LoggedInUser String username, Context context) throws Exception { String fileLocation = ""; // Make sure the context really is a multipart context... if (context.isMultipart()) { Picture pic = new Picture(); // This is the iterator we can use to iterate over the // contents of the request. FileItemIterator fileItemIterator = context.getFileItemIterator(); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); String contentType = item.getContentType(); if (item.isFormField()) { String value = Streams.asString(stream); switch (name) { case "name": pic.setName(value);/*from w ww. ja v a2 s .c o m*/ break; case "about": pic.setAbout(value); break; } } else { OutputStream outputStream = null; try { fileLocation = "public/pictures/" + item.getName(); outputStream = new FileOutputStream(new File(fileLocation)); int read = 0; byte[] bytes = new byte[1024]; while ((read = stream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } pic.setFile(item.getName()); } catch (IOException e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { // outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } pictureDao.postArticlePicture(username, pic); } reziseImage(fileLocation); // We always return ok. You don't want to do that in production ;) return Results.redirect("/picture/all"); }
From source file:de.mpg.imeji.presentation.upload.UploadBean.java
public void upload() throws Exception { HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();/*from w ww. j a v a2 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:n3phele.backend.RepoProxy.java
@POST @Path("{id}/upload/{bucket}") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response upload(@PathParam("id") Long id, @PathParam("bucket") String bucket, @QueryParam("name") String destination, @QueryParam("expires") long expires, @QueryParam("signature") String signature, @Context HttpServletRequest request) throws NotFoundException { Repository repo = Dao.repository().load(id); if (!checkTemporaryCredential(expires, signature, repo.getCredential().decrypt().getSecret(), bucket + ":" + destination)) { log.severe("Expired temporary authorization"); throw new NotFoundException(); }/*from ww w. j a va2 s .com*/ try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); log.info("FileSizeMax =" + upload.getFileSizeMax() + " SizeMax=" + upload.getSizeMax() + " Encoding " + upload.getHeaderEncoding()); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { log.info("FieldName: " + item.getFieldName() + " value:" + Streams.asString(item.openStream())); } else { InputStream stream = item.openStream(); log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName() + " content " + item.getContentType()); URI target = CloudStorage.factory().putObject(repo, stream, item.getContentType(), destination); Response.created(target).build(); } } } catch (Exception e) { log.log(Level.WARNING, "Processing error", e); } return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build(); }
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 ww w . j a v a2 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: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;/*from w w 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:com.cognifide.aet.executor.SuiteServlet.java
private Map<String, String> getRequestData(HttpServletRequest request) { Map<String, String> requestData = new HashMap<>(); ServletFileUpload upload = new ServletFileUpload(); try {/*from w w w .j ava 2s .c o m*/ FileItemIterator itemIterator = upload.getItemIterator(request); while (itemIterator.hasNext()) { FileItemStream item = itemIterator.next(); InputStream itemStream = item.openStream(); String value = Streams.asString(itemStream, CharEncoding.UTF_8); requestData.put(item.getFieldName(), value); } } catch (FileUploadException | IOException e) { LOGGER.error("Failed to process request", e); } return requestData; }