List of usage examples for org.apache.commons.fileupload FileItemStream getName
String getName();
From source file:com.sonicle.webtop.core.app.AbstractEnvironmentService.java
private String findMediaType(FileItemStream fileItem) { String mtype = ServletHelper.guessMediaType(fileItem.getName()); if (!StringUtils.isBlank(mtype)) return mtype; mtype = fileItem.getContentType();/* w w w .j a v a 2 s. c om*/ if (!StringUtils.isBlank(mtype)) return mtype; return "application/octet-stream"; }
From source file:br.com.ifpb.bdnc.projeto.geo.system.MultipartData.java
public String processFile(HttpServletRequest request) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); try {//from w ww . jav a 2 s .c om FileItemIterator itr = upload.getItemIterator(request); while (itr.hasNext()) { FileItemStream item = itr.next(); if (!item.isFormField()) { String path = request.getServletContext().getRealPath("/"); String nameToSave = "profileImage" + Calendar.getInstance().getTimeInMillis() + item.getName(); if (saveImage(path + "/userImages", item, nameToSave)) { return folder + "/" + nameToSave; } } } } catch (FileUploadException ex) { System.out.println("erro ao obter informaoes sobre o arquivo"); } } else { System.out.println("Erro no formulario!"); } return null; }
From source file:foo.domaintest.http.HttpApiModule.java
@Provides @Singleton/*from w ww .ja v a 2 s .co m*/ Multimap<String, String> provideParameterMap(@RequestData("queryString") String queryString, @RequestData("postBody") Lazy<String> lazyPostBody, @RequestData("charset") String requestCharset, FileItemIterator multipartIterator) { // Calling request.getParameter() or request.getParameterMap() etc. consumes the POST body. If // we got the "postpayload" param we don't want to parse the body, so use only the query params. // Note that specifying both "payload" and "postpayload" will result in the "payload" param // being honored and the POST body being completely ignored. ImmutableMultimap.Builder<String, String> params = new ImmutableMultimap.Builder<>(); Multimap<String, String> getParams = parseQuery(queryString); params.putAll(getParams); if (getParams.containsKey("postpayload")) { // Treat the POST body as if it was the "payload" param. return params.put("payload", nullToEmpty(lazyPostBody.get())).build(); } // No "postpayload" so it's safe to consume the POST body and look for params there. if (multipartIterator == null) { // Handle GETs and form-urlencoded POST requests. params.putAll(parseQuery(nullToEmpty(lazyPostBody.get()))); } else { // Handle multipart/form-data requests. try { while (multipartIterator != null && multipartIterator.hasNext()) { FileItemStream item = multipartIterator.next(); try (InputStream stream = item.openStream()) { params.put(item.isFormField() ? item.getFieldName() : item.getName(), CharStreams.toString(new InputStreamReader(stream, requestCharset))); } } } catch (FileUploadException | IOException e) { // Ignore the failure and fall through to return whatever params we managed to parse. } } return params.build(); }
From source file:freedots.web.MusicXML2BrailleServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Score score = null;//from ww w . ja va 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:com.github.davidcarboni.encryptedfileupload.SizesTest.java
@Test public void testMaxSizeLimitUnknownContentLength() throws IOException, FileUploadException { final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file1\"; filename=\"foo1.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "Content-Length: 10\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234\r\n" + "Content-Disposition: form-data; name=\"file2\"; filename=\"foo2.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234--\r\n"; ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(-1);/*from w w w. java2 s. c om*/ upload.setSizeMax(300); // the first item should be within the max size limit // set the read limit to 10 to simulate a "real" stream // otherwise the buffer would be immediately filled MockHttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); req.setContentLength(-1); req.setReadLimit(10); FileItemIterator it = upload.getItemIterator(req); assertTrue(it.hasNext()); FileItemStream item = it.next(); assertFalse(item.isFormField()); assertEquals("file1", item.getFieldName()); assertEquals("foo1.tab", item.getName()); { @SuppressWarnings("resource") // Streams.copy closes the input file InputStream stream = item.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Streams.copy(stream, baos, true); } // the second item is over the size max, thus we expect an error try { // the header is still within size max -> this shall still succeed assertTrue(it.hasNext()); } catch (Exception e) { // FileUploadBase.SizeException has protected access: if (e.getClass().getSimpleName().equals("SizeException")) { fail(); } else { throw e; } } item = it.next(); try { @SuppressWarnings("resource") // Streams.copy closes the input file InputStream stream = item.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Streams.copy(stream, baos, true); fail(); } catch (FileUploadIOException e) { // expected } }
From source file:com.runwaysdk.web.WebFileUploadServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST); // capture the session id boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { // TODO Change exception type String msg = "The HTTP Request must contain multipart content."; throw new RuntimeException(msg); }/*from w ww. ja va 2s .co m*/ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); try { // Parse the request FileItemIterator iter = upload.getItemIterator(req); String fileName = null; String extension = null; InputStream stream = null; String uploadPath = null; while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream input = item.openStream(); if (item.isFormField() && item.getFieldName().equals(WEB_FILE_UPLOAD_PATH_FIELD_NAME)) { uploadPath = Streams.asString(input); } else if (!item.isFormField()) { String fullName = item.getName(); int extensionInd = fullName.lastIndexOf("."); fileName = fullName.substring(0, extensionInd); extension = fullName.substring(extensionInd + 1); stream = input; } } if (stream != null) { clientRequest.newFile(uploadPath, fileName, extension, stream); } } catch (FileUploadException e) { throw new FileWriteExceptionDTO(e.getLocalizedMessage()); } }
From source file:de.egore911.opengate.FileuploadServletRequest.java
public static FileuploadServletRequest wrap(HttpServletRequest req, User user) throws ServletException, IOException { if (req.getContentType().toLowerCase(Locale.ENGLISH).startsWith(FileUploadBase.MULTIPART)) { Map<String, Object> parameters = new HashMap<String, Object>(); Map<String, List<String>> parameterValues = new HashMap<String, List<String>>(); ServletFileUpload upload = new ServletFileUpload(); try {//www .ja v a 2 s . c om FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream stream = iter.next(); InputStream s = stream.openStream(); try { String fieldName = stream.getFieldName(); if (stream.isFormField()) { if (parameters.containsKey(fieldName)) { if (!parameterValues.containsKey(fieldName)) { parameterValues.put(fieldName, new ArrayList<String>()); parameterValues.get(fieldName).add((String) parameters.get(fieldName)); } parameterValues.get(fieldName).add(IOUtils.toString(s)); } else { parameters.put(fieldName, IOUtils.toString(s)); } } else { byte[] byteArray = IOUtils.toByteArray(s); if (byteArray.length > 0) { BinaryData binaryData = new BinaryData(); binaryData.setData(new Blob(byteArray)); binaryData.setMimetype(stream.getContentType()); binaryData.setFilename(stream.getName()); binaryData.setSize(byteArray.length); AbstractEntity.setCreated(binaryData, user); parameters.put(fieldName, binaryData); } } } finally { s.close(); } } } catch (FileUploadException e) { throw new ServletException(e); } return new FileuploadServletRequest(parameters, parameterValues); } else { return new FileuploadServletRequest(req); } }
From source file:de.mpg.imeji.presentation.upload.UploadBean.java
public void upload() throws Exception { HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();/* w ww. ja v a 2s. c om*/ 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:jetbrick.web.mvc.multipart.CommonsFileUpload.java
@Override public MultipartRequest transform(HttpServletRequest request) throws IOException { String contextType = request.getHeader("Content-Type"); if (contextType == null || !contextType.startsWith("multipart/form-data")) { return null; }/*from w ww. j a v a 2 s. c om*/ String encoding = request.getCharacterEncoding(); MultipartRequest req = new MultipartRequest(request); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding(encoding); try { FileItemIterator it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream item = it.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); try { if (item.isFormField()) { req.setParameter(fieldName, Streams.asString(stream, encoding)); } else { String originalFilename = item.getName(); if (originalFilename == null || originalFilename.length() == 0) { continue; } File diskFile = UploadUtils.getUniqueTemporaryFile(originalFilename); OutputStream fos = new FileOutputStream(diskFile); try { IoUtils.copy(stream, fos); } finally { IoUtils.closeQuietly(fos); } FilePart filePart = new FilePart(fieldName, originalFilename, diskFile); req.addFile(filePart); } } finally { IoUtils.closeQuietly(stream); } } } catch (FileUploadException e) { throw new IllegalStateException(e); } return req; }
From source file:ca.nrc.cadc.beacon.web.resources.FileItemServerResource.java
/** * Perform the actual upload.//w ww.j a v a2 s.c o m * * @param fileItemStream The upload file item stream. * @return The URI to the new node. * @throws IOException If anything goes wrong. */ VOSURI upload(final FileItemStream fileItemStream) throws IOException, IllegalArgumentException, NodeAlreadyExistsException { final String filename = fileItemStream.getName(); if (fileValidator.validateString(filename)) { final String path = getCurrentItemURI().getPath() + "/" + URLEncoder.encode(filename, "UTF-8"); final DataNode dataNode = new DataNode(toURI(path)); // WebRT 19564: Add content type to the response of // uploaded items. final List<NodeProperty> properties = new ArrayList<>(); properties.add(new NodeProperty(VOS.PROPERTY_URI_TYPE, fileItemStream.getContentType())); properties.add(new NodeProperty(VOS.PROPERTY_URI_CONTENTLENGTH, Long.toString(getRequest().getEntity().getSize()))); dataNode.setProperties(properties); try (final InputStream inputStream = fileItemStream.openStream()) { upload(inputStream, dataNode); } return dataNode.getUri(); } else { throw new IllegalArgumentException("Name is required and cannot contain characters \n" + "outside of alphanumeric and _-()=+!,;:@&*$."); } }