Example usage for org.apache.commons.fileupload FileItem getInputStream

List of usage examples for org.apache.commons.fileupload FileItem getInputStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getInputStream.

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:org.activiti.rest.service.api.runtime.task.TaskAttachmentCollectionResource.java

protected AttachmentResponse createBinaryAttachment(Representation representation, Task task)
        throws FileUploadException, IOException {
    RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory());
    List<FileItem> items = upload.parseRepresentation(representation);

    String name = null;/*from   w w w  . j  a  v a 2s  . c  om*/
    String description = null;
    String type = null;
    FileItem uploadItem = null;

    for (FileItem fileItem : items) {
        if (fileItem.isFormField()) {
            if ("name".equals(fileItem.getFieldName())) {
                name = fileItem.getString("UTF-8");
            } else if ("description".equals(fileItem.getFieldName())) {
                description = fileItem.getString("UTF-8");
            } else if ("type".equals(fileItem.getFieldName())) {
                type = fileItem.getString("UTF-8");
            }
        } else if (fileItem.getName() != null) {
            uploadItem = fileItem;
        }
    }

    if (name == null) {
        throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }

    if (uploadItem == null) {
        throw new ActivitiIllegalArgumentException("Attachment content is required.");
    }

    Attachment createdAttachment = ActivitiUtil.getTaskService().createAttachment(type, task.getId(),
            task.getProcessInstanceId(), name, description, uploadItem.getInputStream());

    setStatus(Status.SUCCESS_CREATED);
    return getApplication(ActivitiRestServicesApplication.class).getRestResponseFactory()
            .createAttachmentResponse(this, createdAttachment);
}

From source file:org.activityinfo.server.attachment.AppEngineAttachmentService.java

@Override
public void upload(String key, FileItem fileItem, InputStream uploadingStream) {
    try {/*from   ww w. j a v  a2  s . com*/

        GSFileOptionsBuilder builder = new GSFileOptionsBuilder().setBucket("activityinfo-attachments")
                .setKey(key).setContentDisposition("attachment; filename=\"" + fileItem.getName() + "\"")
                .setMimeType(fileItem.getContentType());

        FileService fileService = FileServiceFactory.getFileService();
        AppEngineFile writableFile = fileService.createNewGSFile(builder.build());
        boolean lock = true;
        FileWriteChannel writeChannel = fileService.openWriteChannel(writableFile, lock);
        OutputStream os = Channels.newOutputStream(writeChannel);
        ByteStreams.copy(fileItem.getInputStream(), os);
        os.flush();
        writeChannel.closeFinally();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.activityinfo.server.attachment.AttachmentServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from  w  w  w  .jav  a 2s . c  o  m*/
        String key = request.getParameter("blobId");
        Integer siteId = Integer.valueOf(request.getParameter("siteId"));

        FileItem fileItem = getFirstUploadFile(request);

        String fileName = fileItem.getName();
        InputStream uploadingStream = fileItem.getInputStream();

        service.upload(key, fileItem, uploadingStream);

        CreateSiteAttachment siteAttachment = new CreateSiteAttachment();
        siteAttachment.setSiteId(siteId);
        siteAttachment.setBlobId(key);
        siteAttachment.setFileName(fileName);
        siteAttachment.setBlobSize(fileItem.getSize());
        siteAttachment.setContentType(fileItem.getContentType());

        dispatcher.execute(siteAttachment);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Error handling upload", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.akaza.openclinica.bean.rule.FileUploadHelper.java

private File processUploadedFile(FileItem item, String dirToSaveUploadedFileIn) {
    dirToSaveUploadedFileIn = dirToSaveUploadedFileIn == null ? System.getProperty("java.io.tmpdir")
            : dirToSaveUploadedFileIn;//from w  w  w .  ja  v  a  2  s. c  om
    String fileName = item.getName();
    // Some browsers IE 6,7 getName returns the whole path
    int startIndex = fileName.lastIndexOf('\\');
    if (startIndex != -1) {
        fileName = fileName.substring(startIndex + 1, fileName.length());
    }

    File uploadedFile = new File(dirToSaveUploadedFileIn + File.separator + fileName);
    if (fileRenamePolicy != null) {
        try {
            uploadedFile = fileRenamePolicy.rename(uploadedFile, item.getInputStream());
        } catch (IOException e) {
            throw new OpenClinicaSystemException(e.getMessage());
        }
    }
    try {
        item.write(uploadedFile);
    } catch (Exception e) {
        throw new OpenClinicaSystemException(e.getMessage());
    }
    return uploadedFile;

}

From source file:org.ala.layers.web.ShapesService.java

@RequestMapping(value = "/shape/upload/shp", method = RequestMethod.POST)
@ResponseBody//w  w  w  .j av  a 2s  .c o m
public Map<Object, Object> uploadShapeFile(HttpServletRequest req, HttpServletResponse resp,
        @RequestParam(value = "user_id", required = false) String userId,
        @RequestParam(value = "api_key", required = false) String apiKey) throws Exception {
    // Use linked hash map to maintain key ordering
    Map<Object, Object> retMap = new LinkedHashMap<Object, Object>();

    File tmpZipFile = File.createTempFile("shpUpload", ".zip");

    if (!ServletFileUpload.isMultipartContent(req)) {
        String jsonRequestBody = IOUtils.toString(req.getReader());

        JSONRequestBodyParser reqBodyParser = new JSONRequestBodyParser();
        reqBodyParser.addParameter("user_id", String.class, false);
        reqBodyParser.addParameter("shp_file_url", String.class, false);
        reqBodyParser.addParameter("api_key", String.class, false);

        if (reqBodyParser.parseJSON(jsonRequestBody)) {

            String shpFileUrl = (String) reqBodyParser.getParsedValue("shp_file_url");
            userId = (String) reqBodyParser.getParsedValue("user_id");
            apiKey = (String) reqBodyParser.getParsedValue("api_key");

            if (!checkAPIKey(apiKey, userId)) {
                retMap.put("error", "Invalid user ID or API key");
                return retMap;
            }

            // Use shape file url from json body
            IOUtils.copy(new URL(shpFileUrl).openStream(), new FileOutputStream(tmpZipFile));
            retMap.putAll(handleZippedShapeFile(tmpZipFile));
        } else {
            retMap.put("error", StringUtils.join(reqBodyParser.getErrorMessages(), ","));
        }

    } else {
        if (!checkAPIKey(apiKey, userId)) {
            retMap.put("error", "Invalid user ID or API key");
            return retMap;
        }

        // Create a factory for disk-based file items. File size limit is
        // 50MB
        // Configure a repository (to ensure a secure temp location is used)
        File repository = new File(System.getProperty("java.io.tmpdir"));
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 1024 * 50, repository);

        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List<FileItem> items = upload.parseRequest(req);

        if (items.size() == 1) {
            FileItem fileItem = items.get(0);
            IOUtils.copy(fileItem.getInputStream(), new FileOutputStream(tmpZipFile));
            retMap.putAll(handleZippedShapeFile(tmpZipFile));
        } else {
            retMap.put("error",
                    "Multiple files sent in request. A single zipped shape file should be supplied.");
        }
    }

    return retMap;
}

From source file:org.alfresco.web.app.servlet.JBPMDeployProcessServlet.java

/**
 * Retrieve the JBPM Process Designer deployment archive from the request
 * /* w w w.  j av a2 s .  co m*/
 * @param request  the request
 * @return  the input stream onto the deployment archive
 * @throws WorkflowException
 * @throws FileUploadException
 * @throws IOException
 */
private InputStream getDeploymentArchive(HttpServletRequest request) throws FileUploadException, IOException {
    if (!FileUpload.isMultipartContent(request)) {
        throw new FileUploadException("Not a multipart request");
    }

    GPDUpload fileUpload = new GPDUpload();
    List list = fileUpload.parseRequest(request);
    Iterator iterator = list.iterator();
    if (!iterator.hasNext()) {
        throw new FileUploadException("No process file in the request");
    }

    FileItem fileItem = (FileItem) iterator.next();
    if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) {
        throw new FileUploadException("Not a process archive");
    }

    return fileItem.getInputStream();
}

From source file:org.alfresco.web.bean.wcm.FilePickerBean.java

@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void uploadFile() throws Exception {
    LOGGER.debug(this + ".uploadFile()");
    final FacesContext facesContext = FacesContext.getCurrentInstance();
    final ExternalContext externalContext = facesContext.getExternalContext();
    final HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

    final ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setHeaderEncoding("UTF-8");
    final List<FileItem> fileItems = upload.parseRequest(request);
    final FileUploadBean bean = new FileUploadBean();
    String uploadId = null;/*from   w  w w  .ja v  a  2s.c  om*/
    String currentPath = null;
    String filename = null;
    String returnPage = null;
    InputStream fileInputStream = null;
    for (FileItem item : fileItems) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("item = " + item);
        }
        if (item.isFormField() && item.getFieldName().equals("upload-id")) {
            uploadId = item.getString();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("uploadId is " + uploadId);
            }
        }
        if (item.isFormField() && item.getFieldName().equals("return-page")) {
            returnPage = item.getString();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("returnPage is " + returnPage);
            }
        } else if (item.isFormField() && item.getFieldName().equals("currentPath")) {
            final String previewStorePath = AVMUtil
                    .getCorrespondingPathInPreviewStore(this.getCurrentAVMPath());
            currentPath = AVMUtil.buildPath(previewStorePath, item.getString(),
                    AVMUtil.PathRelation.WEBAPP_RELATIVE);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("currentPath is " + currentPath);
            }
        } else {
            filename = FilenameUtils.getName(item.getName());
            fileInputStream = item.getInputStream();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("uploading file " + filename);
            }
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("saving file " + filename + " to " + currentPath);
    }

    try {
        FileCopyUtils.copy(fileInputStream, this.getAvmService().createFile(currentPath, filename));
        final Map<QName, PropertyValue> props = new HashMap<QName, PropertyValue>(1, 1.0f);
        props.put(ContentModel.PROP_TITLE, new PropertyValue(DataTypeDefinition.TEXT, filename));
        // props.put(ContentModel.PROP_DESCRIPTION,
        // new PropertyValue(DataTypeDefinition.TEXT,
        // "Uploaded for form " + this.xformsSession.getForm().getName()));
        this.getAvmService().setNodeProperties(currentPath + "/" + filename, props);
        this.getAvmService().addAspect(currentPath + "/" + filename, ContentModel.ASPECT_TITLED);

        this.uploads.add(AVMNodeConverter.ToNodeRef(-1, currentPath + "/" + filename));
        returnPage = returnPage.replace("${_FILE_TYPE_IMAGE}", org.alfresco.repo.web.scripts.FileTypeImageUtils
                .getFileTypeImage(facesContext, filename, true));
    } catch (Exception e) {
        LOGGER.debug(e.getMessage(), e);
        returnPage = returnPage.replace("${_UPLOAD_ERROR}", e.getMessage());
    }

    LOGGER.debug("upload complete.  sending response: " + returnPage);
    final org.w3c.dom.Document result = XMLUtil.newDocument();
    final org.w3c.dom.Element htmlEl = result.createElement("html");
    result.appendChild(htmlEl);
    final org.w3c.dom.Element bodyEl = result.createElement("body");
    htmlEl.appendChild(bodyEl);

    final org.w3c.dom.Element scriptEl = result.createElement("script");
    bodyEl.appendChild(scriptEl);
    scriptEl.setAttribute("type", "text/javascript");
    final org.w3c.dom.Node scriptText = result.createTextNode(returnPage);
    scriptEl.appendChild(scriptText);

    final ResponseWriter out = facesContext.getResponseWriter();
    XMLUtil.print(result, out);
}

From source file:org.apache.felix.webconsole.plugins.deppack.internal.WebConsolePlugin.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///  w  w w . jav a 2 s .c  o  m
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // get the uploaded data
    final String action = WebConsoleUtil.getParameter(req, Util.PARAM_ACTION);
    if (ACTION_DEPLOY.equals(action)) {
        Map params = (Map) req.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD);
        if (params != null) {
            final FileItem pck = getFileItem(params, PARAMETER_PCK_FILE, false);
            final DeploymentAdmin admin = (DeploymentAdmin) adminTracker.getService();
            if (admin != null) {
                try {
                    admin.installDeploymentPackage(pck.getInputStream());

                    final String uri = req.getRequestURI();
                    resp.sendRedirect(uri);
                    return;
                } catch ( /*Deployment*/Exception e) {
                    throw new ServletException("Unable to deploy package.", e);
                }
            }
        }
        throw new ServletException("Upload file or deployment admin missing.");
    } else if (ACTION_UNINSTALL.equals(action)) {
        final String pckId = req.getPathInfo().substring(req.getPathInfo().lastIndexOf('/') + 1);
        if (pckId != null && pckId.length() > 0) {
            final DeploymentAdmin admin = (DeploymentAdmin) adminTracker.getService();
            if (admin != null) {
                try {
                    final DeploymentPackage pck = admin.getDeploymentPackage(pckId);
                    if (pck != null) {
                        pck.uninstall();
                    }
                } catch ( /*Deployment*/Exception e) {
                    throw new ServletException("Unable to undeploy package.", e);
                }
            }

        }

        final PrintWriter pw = resp.getWriter();
        pw.println("{ \"reload\":true }");
        return;
    }
    throw new ServletException("Unknown action: " + action);
}

From source file:org.apache.hadoop.hdfs.qjournal.server.UploadImageServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        OutputStream os = null;//from w w w .jav a2 s  .  co  m
        SessionDescriptor sd = null;
        try {
            byte buf[] = new byte[BUFFER_SIZE];

            // parse upload parameters
            UploadImageParam params = new UploadImageParam(request);

            ServletContext context = getServletContext();
            // obtain session descriptor
            if (params.segmentId == 0) {
                // new upload
                sd = startImageUpload(params, context);
            } else {
                // resumed upload
                sd = resumeImageUpload(params, context);
            }

            os = sd.os;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<?> items = upload.parseRequest(request);
            if (items.size() != 1) {
                throwIOException("Should have one item in the multipart contents.");
            }
            FileItem item = (FileItem) items.get(0);

            // write to the local output stream
            if (!item.isFormField()) {
                InputStream is = item.getInputStream();
                int num = 1;
                while (num > 0) {
                    num = is.read(buf);
                    if (num <= 0) {
                        break;
                    }
                    os.write(buf, 0, num);
                }
            }

            // close if needed
            if (params.completed) {
                os.flush();
                sessions.remove(sd.sessionId);
                MD5Hash hash = new MD5Hash(sd.digester.digest());
                os.close();
                InjectionHandler.processEventIO(InjectionEvent.UPLOADIMAGESERVLET_COMPLETE, context, hash);
                // store hash to compare it when rolling the image
                sd.journal.setCheckpointImageDigest(sd.txid, hash);
            }

            // pass the sessionId in the response
            response.setHeader("sessionId", Long.toString(sd.sessionId));
        } catch (Exception e) {
            // cleanup this session
            IOUtils.cleanup(LOG, os);
            sessions.remove(sd != null ? sd.sessionId : -1);
            LOG.error("Error when serving request", e);
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, e.toString());
        }
    } else {
        LOG.error("Error when serving request, not multipart content.");
    }
}

From source file:org.apache.jackrabbit.demo.blog.servlet.BlogAddControllerServlet.java

/**
 * This methods handles POST requests and adds the blog entries according to the parameters in the 
 * request. Request must be multi-part encoded.
 *//*from  w  w  w. j av a 2  s . co m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    List parameters = null;
    String title = null;
    String content = null;
    FileItem image = null;
    FileItem video = null;

    // Check whether the request is multipart encoded
    if (ServletFileUpload.isMultipartContent(request)) {
        DefaultFileItemFactory fileItemFactory = new DefaultFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);

        try {
            // Parse the request and get the paramter set
            parameters = fileUpload.parseRequest(request);
            Iterator paramIter = parameters.iterator();

            // Resolve the parameter set
            while (paramIter.hasNext()) {
                FileItem item = (FileItem) paramIter.next();
                if (item.getFieldName().equalsIgnoreCase("title")) {
                    title = item.getString();
                } else if (item.getFieldName().equalsIgnoreCase("content")) {
                    content = item.getString();
                } else if (item.getFieldName().equalsIgnoreCase("image")) {
                    image = item;
                } else if (item.getFieldName().equalsIgnoreCase("video")) {
                    video = item;
                }
            }

        } catch (FileUploadException e) {
            throw new ServletException("Error occured in processing the multipart request", e);
        }
    } else {
        throw new ServletException("Request is not a multi-part encoded request");
    }

    try {
        //log in to the repository and aquire a session
        Session session = repository.login(new SimpleCredentials("username", "password".toCharArray()));

        String username = (String) request.getSession().getAttribute("username");

        // Only logged in users are allowed to create blog entries
        if (username == null) {
            //set the attributes which are required by user messae page
            request.setAttribute("msgTitle", "Authentication Required");
            request.setAttribute("msgBody", "Only logged in users are allowed to add blog entries.");
            request.setAttribute("urlText", "go back to login page");
            request.setAttribute("url", "/jackrabbit-jcr-demo/blog/index.jsp");

            //forward the request to user massage page
            RequestDispatcher requestDispatcher = this.getServletContext()
                    .getRequestDispatcher("/blog/userMessage.jsp");
            requestDispatcher.forward(request, response);
            return;

        }

        Node blogRootNode = session.getRootNode().getNode("blogRoot");
        Node userNode = blogRootNode.getNode(username);

        // Node to hold the current year
        Node yearNode;
        // Node to hold the current month
        Node monthNode;
        // Node to hold the blog entry to be added
        Node blogEntryNode;
        // Holds the name of the blog entry node
        String nodeName;

        // createdOn property of the blog entry is set to the current time. 
        Calendar calendar = Calendar.getInstance();
        String year = calendar.get(Calendar.YEAR) + "";
        String month = calendar.get(Calendar.MONTH) + "";

        // check whether node exists for current year under usernode and creates a one if not exist
        if (userNode.hasNode(year)) {
            yearNode = userNode.getNode(year);
        } else {
            yearNode = userNode.addNode(year, "nt:folder");
        }

        // check whether node exists for current month under the current year and creates a one if not exist
        if (yearNode.hasNode(month)) {
            monthNode = yearNode.getNode(month);
        } else {
            monthNode = yearNode.addNode(month, "nt:folder");
        }

        if (monthNode.hasNode(title)) {
            nodeName = createUniqueName(title, monthNode);
        } else {
            nodeName = title;
        }

        // creates a blog entry under the current month
        blogEntryNode = monthNode.addNode(nodeName, "blog:blogEntry");
        blogEntryNode.setProperty("blog:title", title);
        blogEntryNode.setProperty("blog:content", content);
        Value date = session.getValueFactory().createValue(Calendar.getInstance());
        blogEntryNode.setProperty("blog:created", date);
        blogEntryNode.setProperty("blog:rate", 0);

        // If the blog entry has an image
        if (image.getSize() > 0) {

            if (image.getContentType().startsWith("image")) {

                Node imageNode = blogEntryNode.addNode("image", "nt:file");
                Node contentNode = imageNode.addNode("jcr:content", "nt:resource");
                contentNode.setProperty("jcr:data", image.getInputStream());
                contentNode.setProperty("jcr:mimeType", image.getContentType());
                contentNode.setProperty("jcr:lastModified", date);
            } else {

                session.refresh(false);

                //set the attributes which are required by user messae page
                request.setAttribute("msgTitle", "Unsupported image format");
                request.setAttribute("msgBody", "The image you attached in not supported");
                request.setAttribute("urlText", "go back to new blog entry page");
                request.setAttribute("url", "/jackrabbit-jcr-demo/blog/addBlogEntry.jsp");

                //forward the request to user massage page
                RequestDispatcher requestDispatcher = this.getServletContext()
                        .getRequestDispatcher("/blog/userMessage.jsp");
                requestDispatcher.forward(request, response);
                return;
            }

        }

        // If the blog entry has a video
        if (video.getSize() > 0) {

            if (video.getName().endsWith(".flv") || video.getName().endsWith(".FLV")) {

                Node imageNode = blogEntryNode.addNode("video", "nt:file");
                Node contentNode = imageNode.addNode("jcr:content", "nt:resource");
                contentNode.setProperty("jcr:data", video.getInputStream());
                contentNode.setProperty("jcr:mimeType", video.getContentType());
                contentNode.setProperty("jcr:lastModified", date);

            } else {

                session.refresh(false);

                //set the attributes which are required by user messae page
                request.setAttribute("msgTitle", "Unsupported video format");
                request.setAttribute("msgBody",
                        "Only Flash videos (.flv) are allowed as video attachement. click <a href=\"www.google.com\">here</a> to covert the videos online.");
                request.setAttribute("urlText", "go back to new blog entry page");
                request.setAttribute("url", "/jackrabbit-jcr-demo/blog/addBlogEntry.jsp");

                //forward the request to user massage page
                RequestDispatcher requestDispatcher = this.getServletContext()
                        .getRequestDispatcher("/blog/userMessage.jsp");
                requestDispatcher.forward(request, response);
                return;
            }
        }

        // persist the changes done
        session.save();

        //set the attributes which are required by user messae page
        request.setAttribute("msgTitle", "Blog entry added succesfully");
        request.setAttribute("msgBody",
                "Blog entry titled \"" + title + "\" was successfully added to your blog space");
        request.setAttribute("urlText", "go back to my blog page");
        request.setAttribute("url", "/jackrabbit-jcr-demo/blog/view");

        //forward the request to user massage page
        RequestDispatcher requestDispatcher = this.getServletContext()
                .getRequestDispatcher("/blog/userMessage.jsp");
        requestDispatcher.forward(request, response);

    } catch (RepositoryException e) {
        throw new ServletException("Repository error occured", e);
    } finally {
        if (session != null) {
            session.logout();
        }
    }
}