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

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

Introduction

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

Prototype

boolean isFormField();

Source Link

Document

Determines whether or not a FileItem instance represents a simple form field.

Usage

From source file:edu.caltech.ipac.firefly.server.servlets.FitsUpload.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {

    File dir = ServerContext.getVisUploadDir();
    File uploadedFile = getUniqueName(dir);

    String overrideKey = req.getParameter("cacheKey");

    DiskFileItemFactory factory = new DiskFileItemFactory();

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

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

    // Process the uploaded items
    Iterator iter = items.iterator();
    FileItem item = null;
    if (iter.hasNext()) {
        item = (FileItem) iter.next();//from  w  w  w  .  ja v  a 2s .c  om

        if (!item.isFormField()) {
            try {
                item.write(uploadedFile);
            } catch (Exception e) {
                sendReturnMsg(res, 500, e.getMessage(), null);
                return;
            }

        }
    }

    if (item == null) {
        sendReturnMsg(res, 500, "Could not find a upload file", null);
        return;
    }

    if (FileUtil.isGZipFile(uploadedFile)) {
        File uploadedFileZiped = new File(uploadedFile.getPath() + "." + FileUtil.GZ);
        uploadedFile.renameTo(uploadedFileZiped);
        FileUtil.gUnzipFile(uploadedFileZiped, uploadedFile, (int) FileUtil.MEG);
    }

    PrintWriter resultOut = res.getWriter();
    String retFile = ServerContext.replaceWithPrefix(uploadedFile);
    UploadFileInfo fi = new UploadFileInfo(retFile, uploadedFile, item.getName(), item.getContentType());
    String fileCacheKey = overrideKey != null ? overrideKey : retFile;
    UserCache.getInstance().put(new StringKey(fileCacheKey), fi);
    resultOut.println(fileCacheKey);
    String size = StringUtils.getSizeAsString(uploadedFile.length(), true);
    Logger.info("Successfully uploaded file: " + uploadedFile.getPath(), "Size: " + size);
    Logger.stats(Logger.VIS_LOGGER, "Fits Upload", "fsize", (double) uploadedFile.length() / StringUtils.MEG,
            "bytes", size);
}

From source file:com.osbitools.ws.shared.prj.web.EntityUtilsMgrWsSrvServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from w w w .j  ava2 s . co m*/
        super.doPost(req, resp);
    } catch (ServletException e) {
        if (e.getCause().getClass().equals(WsSrvException.class)) {
            // Authentication failed
            checkSendError(req, resp, (WsSrvException) e.getCause());
            return;
        } else {
            throw e;
        }
    }

    // Get DsMap name
    String name = req.getParameter(PrjMgrConstants.REQ_NAME_PARAM);

    // Check if rename required

    try {
        if (!ServletFileUpload.isMultipartContent(req)) {
            checkSendError(req, resp, 200, "Request is not multipart");
            return;
        }

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(getDiskFileItemFactory(req));
        InputStream in = null;
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            checkSendError(req, resp, 201, "Error parsing request", null, e);
            return;
        }

        for (FileItem fi : items) {
            if (!fi.isFormField()) {
                in = fi.getInputStream();
                break;
            }
        }

        if (in == null) {
            checkSendError(req, resp, 202, "File Multipart section is not found");
            return;
        }

        boolean minified = isMinfied(req);
        printJson(resp, "{" + Utils.getCRT(minified) + "\"entity\":" + Utils.getSPACE(minified)
                + getEntityUtils(req).create(getPrjRootDir(req), name, in, false, minified) + "}");
        in.close();
    } catch (WsSrvException e) {
        checkSendError(req, resp, e);
    }
}

From source file:cdc.util.Upload.java

public boolean anexos(HttpServletRequest request) throws Exception {
    request.setCharacterEncoding("ISO-8859-1");
    if (ServletFileUpload.isMultipartContent(request)) {
        int cont = 0;
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List fileItemsList = null;
        try {// w  ww  .  j av a2s.  c o  m
            fileItemsList = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String optionalFileName = "";
        FileItem fileItem = null;
        Iterator it = fileItemsList.iterator();
        do {
            //cont++;
            FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
                if (fileItemTemp.getFieldName().equals("file")) {
                    optionalFileName = fileItemTemp.getString();
                }
                parametros.put(fileItemTemp.getFieldName(), fileItemTemp.getString());
            } else {
                fileItem = fileItemTemp;
            }
            if (cont != (fileItemsList.size())) {
                if (fileItem != null) {
                    String fileName = fileItem.getName();
                    if (fileItem.getSize() > 0) {
                        if (optionalFileName.trim().equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                        } else {
                            fileName = optionalFileName;
                        }
                        String dirName = request.getServletContext().getRealPath(pasta);
                        File saveTo = new File(dirName + "/" + fileName);
                        //verificando se a pasta existe. Caso contrrio, criar ela
                        File pasta = new File(dirName);
                        if (!pasta.exists())
                            pasta.mkdirs();//criando a pasta

                        parametros.put("foto", fileName);

                        try {
                            fileItem.write(saveTo);//Escrevendo o arquivo temporrio no diretrio correto
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cont++;
        } while (it.hasNext());
        return true;
    } else {
        return false;
    }
}

From source file:Controller.ControllerImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from www .ja v  a2  s  . co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String code = (String) params.get("txtCode");
                    String name = (String) params.get("txtName");
                    String price = (String) params.get("txtPrice");
                    int a = Integer.parseInt(price);
                    String image = (String) params.get("txtImage");
                    //Update  product
                    if (fileName.equals("")) {

                        Products sp = new Products();
                        sp.Update(code, name, price, image);
                        RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi
                        Products sp = new Products();
                        sp.Update(code, name, price, "upload\\" + fileName);

                        RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

    this.processRequest(request, response);

}

From source file:controller.editGames.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                if (fileItem.isFormField()) {
                    processFormField(fileItem);
                } else {
                    flItem = fileItem;/*www. ja v  a  2  s  .  c  om*/
                }
            }
        }

        Check b = new Check();
        b.setMinCpu(MinCpu);
        b.setMinCpuLvl(MinCpuLvl);
        b.setMinGpu(MinGpu);
        b.setMinGpuLvl(MinGpuLvl);
        b.setMinRam(MinRam);

        b.setCode(Code);

        b.setRecCpuLvl(RecCpuLvl);
        b.setRecCpu(RecCpu);
        b.setRecGpu(RecGpu);
        b.setRecGpuLvl(RecGpuLvl);
        b.setRecRam(RecRam);

        int i = b.editGame();

        if (i > 0) {
            RequestDispatcher rd = request.getRequestDispatcher("viewGames.jsp");
            request.setAttribute("return", "Edit Item is Successful.");
            rd.forward(request, response);
        } else {
            RequestDispatcher rd = request.getRequestDispatcher("editGames.jsp");
            request.setAttribute("return", "Edit Item is Failed.");
            rd.forward(request, response);
        }

    } catch (Exception e) {
        System.out.println(e);

    }
}

From source file:com.flexive.war.servlet.CeFileUpload.java

@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
        throws ServletException, IOException {
    String renderContent = null;//from ww w .  j a  v a  2 s  .c o  m
    try {

        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final BeContentEditorBean ceb = null; // = ContentEditorBean.getSingleton().getInstance(request);

        if (ceb == null) {
            renderContent = "No Content Editor Bean is active";
        } else {

            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();

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

            // Parse the request
            List /* FileItem */ items = upload.parseRequest(request);

            BinaryDescriptor binary = null;

            String xpath = null;
            for (Object item1 : items) {
                FileItem item = (FileItem) item1;
                if (item.isFormField()) {
                    if (item.getFieldName().equalsIgnoreCase("result")) {
                        renderContent = item.getString().replaceAll("\\\\n", "\\\n");
                    } else if (item.getFieldName().equalsIgnoreCase("xpath")) {
                        xpath = item.getString();
                    }
                } else {
                    InputStream uploadedStream = null;
                    try {
                        uploadedStream = item.getInputStream();
                        String name = item.getName();
                        if (name.indexOf('\\') > 0)
                            name = name.substring(name.lastIndexOf('\\') + 1);
                        binary = new BinaryDescriptor(name, item.getSize(), uploadedStream);
                    } finally {
                        if (uploadedStream != null)
                            uploadedStream.close();
                    }
                }
                //                    System.out.println("Item: " + item.getName());
            }

            //FxContent co = ceb.getContent();
            FxBinary binProperty = new FxBinary(binary);
            //co.setValue(xpath, binProperty);
            //ceb.getContentEngine().prepareSave(co);
        }
    } catch (Throwable t) {
        System.err.println(t.getMessage());
        t.printStackTrace();
        renderContent = t.getMessage();
    }

    // Render the result
    PrintWriter w = servletResponse.getWriter();
    if (renderContent == null) {
        renderContent = "No content";
    }
    w.print(renderContent);
    w.close();
    servletResponse.setContentType("text/html");
    servletResponse.setContentLength(renderContent.length());
    ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_OK);
}

From source file:com.openkm.extension.servlet.ZohoFileUploadServlet.java

@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("service({}, {})", request, response);
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    InputStream is = null;/*from   w w w  . j  ava 2s .c  o m*/
    String id = "";

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");

        // Parse the request and get all parameters and the uploaded file
        List<FileItem> items;

        try {
            items = upload.parseRequest(request);
            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();
                if (item.isFormField()) {
                    // if (item.getFieldName().equals("format")) { format =
                    // item.getString("UTF-8"); }
                    if (item.getFieldName().equals("id")) {
                        id = item.getString("UTF-8");
                    }
                    // if (item.getFieldName().equals("filename")) {
                    // filename = item.getString("UTF-8"); }
                } else {
                    is = item.getInputStream();
                }
            }

            // Retrieve token
            ZohoToken zot = ZohoTokenDAO.findByPk(id);

            // Save document
            if (Config.REPOSITORY_NATIVE) {
                String sysToken = DbSessionManager.getInstance().getSystemToken();
                String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode());
                new DbDocumentModule().checkout(sysToken, path, zot.getUser());
                new DbDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser());
            } else {
                String sysToken = JcrSessionManager.getInstance().getSystemToken();
                String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode());
                new JcrDocumentModule().checkout(sysToken, path, zot.getUser());
                new JcrDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser());
            }
        } catch (FileUploadException e) {
            log.error(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        } catch (DatabaseException e) {
            log.error(e.getMessage(), e);
        } catch (FileSizeExceededException e) {
            log.error(e.getMessage(), e);
        } catch (UserQuotaExceededException e) {
            log.error(e.getMessage(), e);
        } catch (VirusDetectedException e) {
            log.error(e.getMessage(), e);
        } catch (VersionException e) {
            log.error(e.getMessage(), e);
        } catch (LockException e) {
            log.error(e.getMessage(), e);
        } catch (AccessDeniedException e) {
            log.error(e.getMessage(), e);
        } catch (ExtensionException e) {
            log.error(e.getMessage(), e);
        } catch (AutomationException e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:com.threecrickets.prudence.util.FormWithFiles.java

/**
 * Constructor./*from   ww  w . j  a va 2 s .c o  m*/
 * 
 * @param webForm
 *        The URL encoded web form
 * @param fileItemFactory
 *        The file item factory
 * @throws ResourceException
 *         In case of an upload handling error
 */
public FormWithFiles(Representation webForm, FileItemFactory fileItemFactory) throws ResourceException {
    if (webForm.getMediaType().includes(MediaType.MULTIPART_FORM_DATA)) {
        RestletFileUpload fileUpload = new RestletFileUpload(fileItemFactory);

        try {
            for (FileItem fileItem : fileUpload.parseRepresentation(webForm)) {
                Parameter parameter;
                if (fileItem.isFormField())
                    parameter = new Parameter(fileItem.getFieldName(), fileItem.getString());
                else {
                    if (fileItem instanceof DiskFileItem) {
                        File file = ((DiskFileItem) fileItem).getStoreLocation();
                        if (file == null)
                            // In memory
                            parameter = new FileParameter(fileItem.getFieldName(), fileItem.get(),
                                    fileItem.getContentType(), fileItem.getSize());
                        else
                            // On disk
                            parameter = new FileParameter(fileItem.getFieldName(), file,
                                    fileItem.getContentType(), fileItem.getSize());
                    } else
                        // Non-file form item
                        parameter = new Parameter(fileItem.getFieldName(), fileItem.getString());
                }

                add(parameter);
            }
        } catch (FileUploadException x) {
            throw new ResourceException(x);
        }
    } else {
        // Default parsing
        addAll(new Form(webForm));
    }
}

From source file:com.ephesoft.dcma.gwt.uploadbatch.server.UploadBatchImageServlet.java

private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService,
        String currentBatchUploadFolderName) throws IOException {
    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;/*www. ja  v a2 s  .  com*/
    InputStream instream = null;
    OutputStream out = null;
    String uploadBatchFolderPath = batchSchemaService.getUploadBatchFolder();
    String uploadFileName = "";
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        uploadFileName = "";
        String uploadFilePath = "";
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);

            for (FileItem item : items) {
                if (!item.isFormField()) { // && "uploadFile".equals(item.getFieldName())) {
                    uploadFileName = item.getName();
                    if (uploadFileName != null) {
                        uploadFileName = uploadFileName
                                .substring(uploadFileName.lastIndexOf(File.separator) + 1);
                    }
                    uploadFilePath = uploadBatchFolderPath + File.separator + currentBatchUploadFolderName
                            + File.separator + uploadFileName;

                    try {
                        instream = item.getInputStream();
                        tempFile = new File(uploadFilePath);

                        out = new FileOutputStream(tempFile);
                        byte buf[] = new byte[1024];
                        int len = instream.read(buf);
                        while (len > 0) {
                            out.write(buf, 0, len);
                            len = instream.read(buf);
                        }
                    } catch (FileNotFoundException e) {
                        LOG.error("Unable to create the upload folder." + e, e);
                        printWriter.write("Unable to create the upload folder.Please try again.");

                    } catch (IOException e) {
                        LOG.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                        if (instream != null) {
                            instream.close();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            LOG.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        }

    } else {
        LOG.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }
    printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName);
    printWriter.append("|");

    printWriter.append("fileName:").append(uploadFileName);
    printWriter.append("|");

    printWriter.flush();
}

From source file:com.tasktop.c2c.server.tasks.web.service.AttachmentUploadController.java

@RequestMapping(value = "", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TextHtmlContentExceptionWrapper {
    try {//from w w  w .j  a v  a  2 s .co  m
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<Attachment> attachments = new ArrayList<Attachment>();
        Map<String, String> formValues = new HashMap<String, String>();

        try {
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {

                if (item.isFormField()) {
                    formValues.put(item.getFieldName(), item.getString());
                } else {
                    Attachment attachment = new Attachment();
                    attachment.setAttachmentData(readInputStream(item.getInputStream()));
                    attachment.setFilename(item.getName());
                    attachment.setMimeType(item.getContentType());
                    attachments.add(attachment);
                }

            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // FIXME better code
            return;
        }

        for (int i = 0; i < attachments.size(); i++) {
            String description = formValues
                    .get(AttachmentUploadUtil.ATTACHMENT_DESCRIPTION_FORM_NAME_PREFIX + i);
            if (description == null) {
                throw new IllegalArgumentException(
                        "Missing description " + i + 1 + " of " + attachments.size());
            }
            attachments.get(0).setDescription(description);
        }

        TaskHandle taskHandle = getTaskHandle(formValues);

        UploadResult result = doUpload(response, attachments, taskHandle);

        response.setContentType("text/html");
        response.getWriter()
                .write(jsonMapper.writeValueAsString(Collections.singletonMap("uploadResult", result)));
    } catch (Exception e) {
        throw new TextHtmlContentExceptionWrapper(e.getMessage(), e);
    }
}