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

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

Introduction

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

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:org.getobjects.appserver.elements.WOFileUpload.java

@Override
public void takeValuesFromRequest(final WORequest _rq, final WOContext _ctx) {
    final Object cursor = _ctx.cursor();

    String formName = this.elementNameInContext(_ctx);
    Object formValue = _rq.formValueForKey(formName);

    if (this.writeValue != null)
        this.writeValue.setValue(formValue, cursor);

    if (formValue == null) {
        if (this.filePath != null)
            this.filePath.setValue(null, cursor);
        if (this.data != null)
            this.data.setValue(null, cursor);
    } else if (formValue instanceof String) {
        /* this happens if the enctype is not multipart/formdata */
        if (this.filePath != null)
            this.filePath.setStringValue((String) formValue, cursor);
    } else if (formValue instanceof FileItem) {
        FileItem fileItem = (FileItem) formValue;

        if (this.size != null)
            this.size.setValue(fileItem.getSize(), cursor);

        if (this.contentType != null)
            this.contentType.setStringValue(fileItem.getContentType(), cursor);

        if (this.filePath != null)
            this.filePath.setStringValue(fileItem.getName(), cursor);

        /* process content */

        if (this.data != null)
            this.data.setValue(fileItem.get(), cursor);
        else if (this.string != null) {
            // TODO: we could support a encoding get-binding
            this.string.setStringValue(fileItem.getString(), cursor);
        } else if (this.inputStream != null) {
            try {
                this.inputStream.setValue(fileItem.getInputStream(), cursor);
            } catch (IOException e) {
                log.error("failed to get input stream for upload file", e);
                this.inputStream.setValue(null, cursor);
            }//from  w w w .  j a  va  2 s.c o  m
        }

        /* delete temporary file */

        if (this.deleteAfterPush != null) {
            if (this.deleteAfterPush.booleanValueInComponent(cursor))
                fileItem.delete();
        }
    } else
        log.warn("cannot process WOFileUpload value: " + formValue);
}

From source file:org.jamwiki.servlets.UploadServlet.java

/**
 *
 *//* ww w. j  a va 2  s.  c  o  m*/
private void upload(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
    String virtualWiki = pageInfo.getVirtualWikiName();
    List<FileItem> fileItems = ServletUtil.processMultipartRequest(request);
    String filename = null;
    String destinationFilename = null;
    String contentType = null;
    long fileSize = 0;
    String contents = null;
    boolean isImage = true;
    File uploadedFile = null;
    String url = null;
    byte buff[] = null;
    for (FileItem fileItem : fileItems) {
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            if (fieldName.equals("description")) {
                // FIXME - these should be parsed
                contents = fileItem.getString("UTF-8");
            } else if (fieldName.equals("destination")) {
                destinationFilename = fileItem.getString("UTF-8");
            }
            continue;
        }
        // file name can have encoding issues, so manually convert
        filename = fileItem.getName();
        if (filename == null) {
            throw new WikiException(new WikiMessage("upload.error.filename"));
        }
        filename = ImageUtil.sanitizeFilename(filename);
        url = ImageUtil.generateFileUrl(virtualWiki, filename, null);
        if (!ImageUtil.isFileTypeAllowed(filename)) {
            String extension = FilenameUtils.getExtension(filename);
            throw new WikiException(new WikiMessage("upload.error.filetype", extension));
        }
        fileSize = fileItem.getSize();
        contentType = fileItem.getContentType();
        if (ImageUtil.isImagesOnFS()) {
            uploadedFile = ImageUtil.buildAbsoluteFile(url);
            fileItem.write(uploadedFile);
            isImage = ImageUtil.isImage(uploadedFile);
        } else {
            buff = fileItem.get();
        }
    }
    if (ImageUtil.isImagesOnFS() && uploadedFile == null) {
        throw new WikiException(new WikiMessage("upload.error.filenotfound"));
    }
    destinationFilename = processDestinationFilename(virtualWiki, destinationFilename, filename);
    String pageName = ImageUtil
            .generateFilePageName((!StringUtils.isEmpty(destinationFilename) ? destinationFilename : filename));
    if (this.handleSpam(request, pageInfo, pageName, contents, null)) {
        if (ImageUtil.isImagesOnFS()) {
            // delete the spam file
            uploadedFile.delete();
        }
        this.view(request, next, pageInfo);
        next.addObject("contents", contents);
        return;
    }
    if (!StringUtils.isEmpty(destinationFilename)) {
        // rename the uploaded file if a destination file name was specified
        filename = ImageUtil.sanitizeFilename(destinationFilename);
        url = ImageUtil.generateFileUrl(virtualWiki, filename, null);
        if (ImageUtil.isImagesOnFS()) {
            File renamedFile = ImageUtil.buildAbsoluteFile(url);
            if (!uploadedFile.renameTo(renamedFile)) {
                throw new WikiException(new WikiMessage("upload.error.filerename", destinationFilename));
            }
        }
    }
    ImageData imageData = null;
    if (!ImageUtil.isImagesOnFS()) {
        imageData = processImageData(contentType, buff);
        isImage = (imageData.width >= 0);
    }
    String ipAddress = ServletUtil.getIpAddress(request);
    WikiUser user = ServletUtil.currentWikiUser();
    Topic topic = ImageUtil.writeImageTopic(virtualWiki, pageName, contents, user, isImage, ipAddress);
    WikiFileVersion wikiFileVersion = new WikiFileVersion();
    wikiFileVersion.setUploadComment(topic.getTopicContent());
    ImageUtil.writeWikiFile(topic, wikiFileVersion, user, ipAddress, filename, url, contentType, fileSize,
            imageData);
    ServletUtil.redirect(next, virtualWiki, topic.getName());
}

From source file:org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl.java

@DataBoundConstructor
public FileCredentialsImpl(@CheckForNull CredentialsScope scope, @CheckForNull String id,
        @CheckForNull String description, @Nonnull FileItem file, @CheckForNull String fileName,
        @CheckForNull String data) throws IOException {
    super(scope, id, description);
    String name = file.getName();
    if (name.length() > 0) {
        this.fileName = name.replaceFirst("^.+[/\\\\]", "");
        byte[] unencrypted = file.get();
        try {/*from  w  w  w.  j a va2 s  . c o m*/
            this.data = KEY.encrypt().doFinal(unencrypted);
        } catch (GeneralSecurityException x) {
            throw new IOException2(x);
        }
    } else {
        this.fileName = fileName;
        this.data = Base64.decodeBase64(data);
    }
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "for {0} have {1} of length {2} after upload of {3}",
                new Object[] { getId(), this.fileName, unencrypted().length, name });
    }
}

From source file:org.karsha.controler.UploadDocumentServlet.java

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

    SecurityManager sm = System.getSecurityManager();

    HttpSession session = request.getSession();
    String userPath = request.getServletPath();
    String url = "";
    List items = null;//from   w  w  w  . jav  a 2s  . c o m

    if (userPath.equals("/uploaddocuments")) {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(5000000);
            //  FileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                // items = upload.
                items = upload.parseRequest(request);
            } catch (Exception ex) {
                Logger.getLogger(UploadDocumentServlet.class.getName()).log(Level.SEVERE, null, ex);
            }

            HashMap requestParameters = new HashMap();

            try {

                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {

                    FileItem item = (FileItem) iterator.next();

                    if (item.isFormField()) {

                        requestParameters.put(item.getFieldName(), item.getString());

                    } else {
                        PDFBookmark pdfBookmark = new PDFBookmark();
                        byte[] fileContent = item.get();
                        LinkedHashMap<String, String> docSectionMap = pdfBookmark
                                .splitPDFByBookmarks(fileContent);

                        if (!docSectionMap.isEmpty()) {

                            Document newDocument = new Document();
                            newDocument.setDocumentName(requestParameters.get("docName").toString());
                            newDocument.setUserId(Integer.parseInt(session.getAttribute("userId").toString()));
                            String a = requestParameters.get("collection_type_new").toString();
                            newDocument.setCollectionId(Integer.parseInt(a));
                            //  newDocument.setDocumentContent(fileContent);

                            request.setAttribute("requestParameters", requestParameters);

                            if (DocumentDB.isFileNameDuplicate(newDocument.getDocumentName())) {
                                url = "/WEB-INF/view/uploaddoc.jsp?error=File name already exists, please enter another file name";
                            } else {
                                //DocumentDB.insert(newDocument);
                                DocumentDB.insertDocMetaData(newDocument);
                                int docId = DocumentDB
                                        .getDocumentDataByDocName(requestParameters.get("docName").toString())
                                        .getDocId();

                                DocSection docSection = new DocSection();
                                for (Map.Entry entry : docSectionMap.entrySet()) {
                                    docSection.setParentDocId(docId);
                                    docSection.setSectionName((String) entry.getKey());
                                    byte[] byte1 = ((String) entry.getValue()).getBytes();
                                    docSection.setSectionContent(byte1);
                                    docSection.setUserId(
                                            Integer.parseInt(session.getAttribute("userId").toString()));
                                    //To-Do set this correctly
                                    //docSection.setSectionCatog(Integer.parseInt(session.getAttribute("sectioncat").toString()));
                                    docSection.setSectionCatog(4);
                                    DocSectionDB.insert(docSection);

                                }

                                url = "/WEB-INF/view/uploaddoc.jsp?succuss=File Uploaded Successfully";
                            }

                        } /*
                          * check wheter text can be extracted
                          */ /*
                              * if(DocumentValidator.isDocValidated(fileContent)){
                              *
                              *
                              * Document newDocument = new Document();
                              * newDocument.setDocumentName(requestParameters.get("docName").toString());
                              * newDocument.setUserId(Integer.parseInt(session.getAttribute("userId").toString()));
                              * String a =
                              * requestParameters.get("collection_type_new").toString();
                              * newDocument.setCollectionId(Integer.parseInt(a));
                              * newDocument.setDocumentContent(fileContent);
                              *
                              * request.setAttribute("requestParameters",
                              * requestParameters);
                              *
                              * if
                              * (DocumentDB.isFileNameDuplicate(newDocument.getDocumentName()))
                              * { url = "/WEB-INF/view/uploaddoc.jsp?error=File
                              * name already exists, please enter another file
                              * name"; } else { //DocumentDB.insert(newDocument);
                              * DocumentDB.insertDocMetaData(newDocument); url =
                              * "/WEB-INF/view/uploaddoc.jsp?succuss=File
                              * Uploaded Successfully"; }
                              *
                              *
                              * }
                              *
                              */ else {
                            url = "/WEB-INF/view/uploaddoc.jsp?error=Text can't be extracted from file, Please try onother";
                        }

                    }

                }

            } //                    catch (FileUploadException e) {
              //                        e.printStackTrace();
              //                        
              //                        
              //                    }
              //                    
            catch (Exception e) {

                e.printStackTrace();
            }
        }

        request.getRequestDispatcher(url).forward(request, response);

    }

}

From source file:org.kie.workbench.common.forms.jbpm.server.service.impl.documents.storage.FormsDocumentServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Map<String, Object> response = new HashMap<>();

    try {/*from www .  ja  v  a 2 s.com*/

        FileItem fileItem = getFileItem(req);

        String id = UUID.randomUUID().toString();

        String content = Base64.getEncoder().encodeToString(fileItem.get());

        DocumentUploadChunk chunk = new DocumentUploadChunk(id, fileItem.getName(), 0, 1, content);

        DocumentUploadSession session = new DocumentUploadSession(chunk.getDocumentId(),
                chunk.getDocumentName(), chunk.getMaxChunks());

        session.add(chunk);

        storage.uploadContentChunk(chunk);

        session.setState(DocumentUploadSession.State.MERGING);

        storage.merge(session);

        DocumentData data = new DocumentData(id, fileItem.getName(), fileItem.getSize(), "",
                System.currentTimeMillis());

        response.put("document", data);
    } catch (Exception e) {
        response.put("error", "error");
    } finally {
        writeResponse(resp, response);
    }
}

From source file:org.mentawai.rule.ImageMinSizeRule.java

public boolean check(String field, Action action) {

    Input input = action.getInput();/* w w  w  . java2 s  .  c  om*/

    Object value = input.getValue(field);

    if (value == null || value.toString().trim().equals("")) {

        // if we got to this point, it means that there is no RequiredRule
        // in front of this rule. Therefore this field is probably an OPTIONAL
        // field, so if it is NULL or EMPTY we don't want to do any
        // futher validation and return true to allow it.

        return true; // may be optional
    }

    if (value instanceof FileItem) {

        FileItem item = (FileItem) value;

        byte[] data = item.get();

        if (item.getSize() <= 0 || data == null || data.length <= 0) {

            throw new org.mentawai.util.RuntimeException("Cannot find image file to validate: " + field);

        }

        Dimension d = ImageUtils.getSize(data);

        if (d.getWidth() < width || d.getHeight() < height)
            return false;

        return true;

    } else {

        throw new org.mentawai.util.RuntimeException("Bad type for file upload: " + value.getClass());
    }
}

From source file:org.mhi.imageutilities.FileHandler.java

public String getParameter(String field_name) throws UnsupportedEncodingException {
    String result = null;/* ww  w .  j  a v a  2s  .c o  m*/
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();
        if (item.getFieldName().equals(field_name)) {
            result = new String(item.get(), "UTF-8");

        }
    }
    return result;
}

From source file:org.mikha.utils.web.examples.FormsServlet.java

/**
 * Parses "file" form.// w ww .  j a  v  a 2  s .c  o  m
 * @param req request
 * @param rsp response
 * @throws ServletException if failed to forward
 * @throws IOException if failed to forward
 */
@ControllerMethodMapping(paths = "/file")
public String parseFileForm(HttpParamsRequest req, HttpServletResponse rsp)
        throws ServletException, IOException {
    String submit = req.getParameter("submit");

    if (submit != null) {
        FileItem file = req.getFile("file");
        if (!req.hasRecentErrors()) {
            rsp.setContentType(file.getContentType());
            rsp.setContentLength((int) file.getSize());
            rsp.getOutputStream().write(file.get());
            return null;
        }
    }

    return "fileform.jsp";
}

From source file:org.mikha.utils.web.examples.MultipartServlet.java

protected void doPost(HttpParamsRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    FileItem file = request.getFile("myfile");
    if (file == null) {
        throw new ServletException("File \"myfile\" is not found in uploaded data");
    }//  w w w .  ja  va 2  s. c  o m

    response.setContentType(file.getContentType());
    response.setContentLength((int) file.getSize());
    response.getOutputStream().write(file.get());
}

From source file:org.mitre.mrald.util.FileUtils.java

/**
 *  Stores the image to disk. Note this will handle only one file at a time. If
 *  you want to upload more than one image, you'll have to rework this. The
 *  first non-form item encountered (a file field) is the one taken.
 *
 *@param  req                      Request that contains the upload
 *@param  user                     Description of the Parameter
 *@return                          Description of the Return Value
 *@exception  JspException         Description of the Exception
 *@exception  FileUploadException  Description of the Exception
 *@exception  IOException          Description of the Exception
 *@exception  Exception            Description of the Exception
 *@since/* w  w  w. j a v a2s  .co  m*/
 */
@Deprecated
public void uploadFile(HttpServletRequest req, User user)
        throws MraldException, FileUploadException, IOException, Exception {
    if (!FileUpload.isMultipartContent(req)) {
        throw new MraldException("The supplied request did not come from a multipart request - "
                + "there can't be any file buried in here.");
    }
    /*
     *  parse the request
     */
    DiskFileUpload upload = new DiskFileUpload();
    List items = upload.parseRequest(req);
    Iterator iter = items.iterator();

    String fileName = "";

    while (iter.hasNext()) {

        FileItem fileSetItem = (FileItem) iter.next();
        String itemName = fileSetItem.getFieldName();

        if (itemName.startsWith("fileName")) {
            fileName = fileSetItem.get().toString();

        }
    }

    items.iterator();
    while (iter.hasNext()) {
        FileItem fileSetItem = (FileItem) iter.next();
        String itemName = fileSetItem.getFieldName();

        if (itemName.startsWith("settings")) {

            String dirFileName = Config.getProperty("BasePath");

            File fileFinalLocation = new File(dirFileName + "/" + fileName);
            fileSetItem.write(fileFinalLocation);
        }
    }
}