List of usage examples for org.apache.commons.fileupload.util Streams copy
public static long copy(InputStream pInputStream, OutputStream pOutputStream, boolean pClose) throws IOException
From source file:org.kaaproject.kaa.server.admin.servlet.FileUpload.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //CHECKSTYLE:ON ServletFileUpload upload = new ServletFileUpload(); try {/*from www. j a va2 s . c om*/ FileItemIterator iter = upload.getItemIterator(request); if (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); LOG.debug("Uploading file '{}' with item name '{}'", item.getName(), name); InputStream stream = item.openStream(); // Process the input stream ByteArrayOutputStream out = new ByteArrayOutputStream(); Streams.copy(stream, out, true); byte[] data = out.toByteArray(); cacheService.uploadedFile(name, data); } else { LOG.error("No file found in post request!"); throw new RuntimeException("No file found in post request!"); } } catch (Exception ex) { LOG.error("Unexpected error in FileUpload.doPost: ", ex); throw new RuntimeException(ex); } }
From source file:org.wyona.yanel.impl.resources.node.NodeResource.java
/** * @see org.wyona.yanel.core.api.attributes.CreatableV2#create(HttpServletRequest) *///from w ww.jav a2 s . c o m public void create(HttpServletRequest request) { try { Repository repo = getRealm().getRepository(); if (request instanceof HttpRequest) { HttpRequest yanelRequest = (HttpRequest) request; if (yanelRequest.isMultipartRequest()) { Enumeration parameters = yanelRequest.getFileNames(); if (parameters.hasMoreElements()) { String name = (String) parameters.nextElement(); Node newNode = org.wyona.yanel.core.util.YarepUtil.addNodes(repo, getPath().toString(), org.wyona.yarep.core.NodeType.RESOURCE); OutputStream output = newNode.getOutputStream(); InputStream is = yanelRequest.getInputStream(name); Streams.copy(is, output, true); uploadMimeType = yanelRequest.getContentType(name); String suffix = org.wyona.commons.io.PathUtil.getSuffix(newNode.getPath()); if (suffix != null) { if (!getMimeTypeBySuffix(suffix).equals(uploadMimeType)) { log.warn("Upload request content type '" + uploadMimeType + "' is NOT the same as the guessed mime type '" + getMimeTypeBySuffix(suffix) + "' based on the suffix (Path: " + newNode.getPath() + ")"); } } newNode.setMimeType(uploadMimeType); } } else { log.error("this is NOT a multipart request"); } } else { log.error("this is NOT a HttpRequest"); } // TODO: Introspection should not be hardcoded! /* String name = new org.wyona.commons.io.Path(getPath()).getName(); String parent = new org.wyona.commons.io.Path(getPath()).getParent().toString(); String nameWithoutSuffix = name; int lastIndex = name.lastIndexOf("."); if (lastIndex > 0) nameWithoutSuffix = name.substring(0, lastIndex); String introspectionPath = parent + "/introspection-" + nameWithoutSuffix + ".xml"; org.wyona.yanel.core.util.YarepUtil.addNodes(repo, introspectionPath, org.wyona.yarep.core.NodeType.RESOURCE); writer = new java.io.OutputStreamWriter(repo.getNode(introspectionPath).getOutputStream()); writer.write(getIntrospection(name)); writer.close();*/ } catch (Exception e) { log.error(e.getMessage(), e); } }
From source file:play.data.parsing.ApacheMultipartParser.java
public Map<String, String[]> parse(InputStream body) { Map<String, String[]> result = new HashMap<String, String[]>(); try {//from w w w . j a v a 2 s. c o m FileItemIteratorImpl iter = new FileItemIteratorImpl(body, Request.current().headers.get("content-type").value(), Request.current().encoding); while (iter.hasNext()) { FileItemStream item = iter.next(); FileItem fileItem = new AutoFileItem(item); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } if (fileItem.isFormField()) { // must resolve encoding String _encoding = Request.current().encoding; // this is our default String _contentType = fileItem.getContentType(); if (_contentType != null) { HTTP.ContentTypeWithEncoding contentTypeEncoding = HTTP.parseContentType(_contentType); if (contentTypeEncoding.encoding != null) { _encoding = contentTypeEncoding.encoding; } } putMapEntry(result, fileItem.getFieldName(), fileItem.getString(_encoding)); } else { @SuppressWarnings("unchecked") List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS"); if (uploads == null) { uploads = new ArrayList<Upload>(); Request.current().args.put("__UPLOADS", uploads); } try { uploads.add(new FileUpload(fileItem)); } catch (Exception e) { // GAE does not support it, we try in memory uploads.add(new MemoryUpload(fileItem)); } putMapEntry(result, fileItem.getFieldName(), fileItem.getFieldName()); } } } catch (FileUploadIOException e) { Logger.debug(e, "error"); throw new IllegalStateException("Error when handling upload", e); } catch (IOException e) { Logger.debug(e, "error"); throw new IllegalStateException("Error when handling upload", e); } catch (FileUploadException e) { Logger.debug(e, "error"); throw new IllegalStateException("Error when handling upload", e); } catch (Exception e) { Logger.debug(e, "error"); throw new UnexpectedException(e); } return result; }
From source file:zutil.jee.upload.AjaxFileUpload.java
@SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileUploadListener listener = new FileUploadListener(); try {/* w w w .j a v a2 s .c o m*/ // Initiate list and HashMap that will contain the data HashMap<String, String> fields = new HashMap<String, String>(); ArrayList<FileItem> files = new ArrayList<FileItem>(); // Add the listener to the session HttpSession session = request.getSession(); LinkedList<FileUploadListener> list = (LinkedList<FileUploadListener>) session .getAttribute(SESSION_FILEUPLOAD_LISTENER); if (list == null) { list = new LinkedList<FileUploadListener>(); session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list); } list.add(listener); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); if (TEMPFILE_PATH != null) factory.setRepository(TEMPFILE_PATH); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setProgressListener(listener); // Set overall request size constraint //upload.setSizeMax(yourMaxRequestSize); // Parse the request FileItemIterator it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream item = it.next(); // Is the file type allowed? if (!item.isFormField() && !ALLOWED_EXTENSIONS.contains(FileUtil.getFileExtension(item.getName()).toLowerCase())) { String msg = "Filetype '" + FileUtil.getFileExtension(item.getName()) + "' is not allowed!"; logger.warning(msg); listener.setStatus(Status.Error); listener.setFileName(item.getName()); listener.setMessage(msg); return; } listener.setFileName(item.getName()); FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), item.getName()); // Read the file data Streams.copy(item.openStream(), fileItem.getOutputStream(), true); if (fileItem instanceof FileItemHeadersSupport) { final FileItemHeaders fih = item.getHeaders(); ((FileItemHeadersSupport) fileItem).setHeaders(fih); } //Handle the item if (fileItem.isFormField()) { fields.put(fileItem.getFieldName(), fileItem.getString()); } else { files.add(fileItem); logger.info("Recieved file: " + fileItem.getName() + " (" + StringUtil.formatByteSizeToString(fileItem.getSize()) + ")"); } } // Process the upload listener.setStatus(Status.Processing); doUpload(request, response, fields, files); // Done listener.setStatus(Status.Done); } catch (Exception e) { logger.log(Level.SEVERE, null, e); listener.setStatus(Status.Error); listener.setFileName(""); listener.setMessage(e.getMessage()); } }