Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:corpixmgr.handler.CorpixPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request//ww  w.jav a 2 s.co  m
 */
protected void parseImportParams(HttpServletRequest request) throws CorpixException {
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //System.out.println("Parsing import params");
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Parse the request
            List items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    if (fieldName != null) {
                        String contents = item.getString("UTF-8");
                        processField(fieldName, contents);
                    }
                } else if (item.getName().length() > 0) {
                    fileName = item.getName();
                    InputStream is = item.getInputStream();
                    ByteArrayOutputStream bh = new ByteArrayOutputStream();
                    while (is.available() > 0) {
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        bh.write(b);
                    }
                    fileData = bh.toByteArray();
                }
            }
        } else {
            Map tbl = request.getParameterMap();
            Set<String> keys = tbl.keySet();
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                String[] values = (String[]) tbl.get(key);
                for (int i = 0; i < values.length; i++)
                    processField(key, values[i]);
            }
        }
    } catch (Exception e) {
        throw new CorpixException(e);
    }
}

From source file:br.com.caelum.vraptor.observer.upload.CommonsUploadMultipartObserver.java

public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config,
        Validator validator) {//from   w  w  w  . j  av a 2 s  .c o  m

    if (!ServletFileUpload.isMultipartContent(request)) {
        return;
    }

    logger.info("Request contains multipart data. Try to parse with commons-upload.");

    final Multiset<String> indexes = HashMultiset.create();
    final Multimap<String, String> params = LinkedListMultimap.create();

    ServletFileUpload uploader = createServletFileUpload(config);
    uploader.setSizeMax(config.getSizeLimit());
    uploader.setFileSizeMax(config.getFileSizeLimit());

    try {
        final List<FileItem> items = uploader.parseRequest(request);
        logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size());

        for (FileItem item : items) {
            String name = item.getFieldName();
            name = fixIndexedParameters(name, indexes);

            if (item.isFormField()) {
                logger.debug("{} is a field", name);
                params.put(name, getValue(item, request));

            } else if (isNotEmpty(item)) {
                logger.debug("{} is a file", name);
                processFile(item, name, request);

            } else {
                logger.debug("A file field is empty: {}", item.getFieldName());
            }
        }

        for (String paramName : params.keySet()) {
            Collection<String> paramValues = params.get(paramName);
            request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()]));
        }

    } catch (final SizeLimitExceededException e) {
        reportSizeLimitExceeded(e, validator);

    } catch (FileUploadException e) {
        reportFileUploadException(e, validator);
    }
}

From source file:it.biblio.servlets.Inserimento_Ristampa.java

/**
 * metodo per gestire l'upload di file// w ww .ja  va2s.  c  o m
 *
 * @param request
 * @param response
 * @param k
 * @return
 * @throws IOException
 */
private boolean upload(HttpServletRequest request) throws IOException, Exception {

    Map<String, Object> ristampe = new HashMap<String, Object>();
    int idopera = Integer.parseInt(request.getParameter("id"));

    if (ServletFileUpload.isMultipartContent(request)) {

        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfo = new ServletFileUpload(fif);
        List<FileItem> items = sfo.parseRequest(request);
        for (FileItem item : items) {
            String fname = item.getFieldName();
            if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) {
                ristampe.put("numpagine", Integer.parseInt(item.getString()));
            } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) {
                ristampe.put("datapub", item.getString());
            } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) {
                ristampe.put("editore", item.getString());
            } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) {
                ristampe.put("lingua", item.getString());
            } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) {
                ristampe.put("indice", item.getString());
                //se  stato inserito un pdf salvo il file e inserisco nella mappa i dati
            } else if (!item.isFormField() && fname.equals("PDF")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF"
                            + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("download", "PDF" + File.separatorChar + name);
                }
                //salvo l'immagine e inserisco i dati nella mappa
            } else if (!item.isFormField() && fname.equals("copertina")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar
                            + "Copertine" + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("copertina", "Copertine" + File.separatorChar + name);
                }
            }
        }
        ristampe.put("pubblicazioni", idopera);
        return Database.insertRecord("ristampe", ristampe);

    }
    return false;
}

From source file:de.fau.amos.FileUpload.java

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

    String pathInfo = request.getPathInfo();
    System.out.println("called fileupload: " + pathInfo);
    boolean isImportProductionData = pathInfo != null && pathInfo.startsWith("/importProductionData");
    boolean isImportEnergyData = pathInfo != null && pathInfo.startsWith("/importEnergyData");

    if (ServletFileUpload.isMultipartContent(request)) {
        try {//from  w  w  w  .j a va  2s.  com
            List<FileItem> list = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem fi : list) {
                if (!fi.isFormField()) {
                    String rand = "";
                    for (int i = 0; i < 6; i++) {
                        rand += (int) (Math.random() * 10);
                    }
                    String plantId = "";
                    if (isImportEnergyData || isImportProductionData) {
                        plantId = request.getPathInfo().replace((isImportEnergyData ? "/importEnergyData"
                                : (isImportProductionData ? "/importProductionData" : "")), "");
                    }
                    if (plantId == null || plantId.length() == 0) {
                        plantId = "";
                        //                  }else{
                        //                     plantId="_"+plantId;
                    }
                    String name = new File(rand + "_" + fi.getName()).getName()
                            + (isImportEnergyData ? "_impED" + plantId
                                    : (isImportProductionData ? "_impPD" + plantId : ""));

                    File folder = null;
                    if (isImportEnergyData || isImportProductionData) {
                        folder = new File(System.getProperty("userdir.location"), "import");
                    } else {
                        folder = new File(System.getProperty("userdir.location"), "uploads");
                    }
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    fi.write(new File(folder, name));
                }
            }

            request.setAttribute("message", "File uploaded successfully");
        } catch (Exception e) {
            request.setAttribute("errorMessage", "File upload failed!");
        }

    } else {
        request.setAttribute("errorMessage", "Something went wrong.");
    }

    if (isImportEnergyData || isImportProductionData) {
        //         request.setAttribute("plant",request.getPathInfo().replace("/import",""));
        //         request.getRequestDispatcher("/intern/import.jsp").forward(request, response);
        response.sendRedirect(request.getContextPath() + "/intern/import.jsp");
    } else {
        response.sendRedirect(request.getContextPath() + "/intern/funktion3.jsp");
    }

}

From source file:com.liteoc.bean.rule.FileUploadHelper.java

public List<File> returnFiles(HttpServletRequest request, ServletContext context,
        String dirToSaveUploadedFileIn) {

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    return isMultipart ? getFiles(request, context, createDirectoryIfDoesntExist(dirToSaveUploadedFileIn))
            : new ArrayList<File>();
}

From source file:com.brokenmodel.swats.RouterServlet.java

private List<FileItem> handleMultipart(HttpServletRequest request) throws Exception {
    List<FileItem> fileItems = new ArrayList<FileItem>();
    if (ServletFileUpload.isMultipartContent(request)) {
        for (Object itemObj : fileUpload.parseRequest(request)) {
            fileItems.add((FileItem) itemObj);
        }/* w w w.  j ava 2 s.c o  m*/
    }
    return fileItems;
}

From source file:com.axway.ats.testexplorer.pages.testcase.attachments.AttachmentsServlet.java

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

    Object checkContextAttribute = request.getSession().getServletContext()
            .getAttribute(ContextListener.getAttachedFilesDir());
    // check if ats-attached-files property is set
    if (checkContextAttribute == null) {
        LOG.error(/*from ww  w .ja v  a 2  s  .c o m*/
                "No attached files could be attached. \nPossible reason could be Tomcat 'CATALINA_HOME' or 'CATALINA_BASE' is not set.");
    } else {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        // Check that we have a file upload request
        if (!ServletFileUpload.isMultipartContent(request)) {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
            return;
        }

        repoFilesDir = checkContextAttribute.toString();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // fileitem containing information about the attached file
        FileItem fileItem = null;
        FileItem currentElement = null;
        String dbName = "";
        String attachedFile = "";
        int runId = 0;
        int suiteId = 0;
        int testcaseId = 0;

        try {
            // Parse the request to get file items.
            List<?> fileItems = upload.parseRequest(request);
            // Process the uploaded file items
            Iterator<?> i = fileItems.iterator();
            while (i.hasNext()) {
                currentElement = (FileItem) i.next();
                // check if this is the attached file
                if ("upfile".equals(currentElement.getFieldName())) {
                    fileItem = currentElement;
                    attachedFile = getFileSimpleName(fileItem.getName());
                    if (attachedFile == null) {
                        break;
                    }
                } else if ("dbName".equals(currentElement.getFieldName())) {
                    if (!StringUtils.isNullOrEmpty(currentElement.getString()))
                        dbName = currentElement.getString();
                } else if ("runId".equals(currentElement.getFieldName())) {
                    runId = getIntValue(currentElement.getString());
                } else if ("suiteId".equals(currentElement.getFieldName())) {
                    suiteId = getIntValue(currentElement.getString());
                } else if ("testcaseId".equals(currentElement.getFieldName())) {
                    testcaseId = getIntValue(currentElement.getString());
                }
            }
            // check if all values are valid
            if (!StringUtils.isNullOrEmpty(attachedFile) && !StringUtils.isNullOrEmpty(dbName) && runId > 0
                    && suiteId > 0 && testcaseId > 0) {
                // copy the attached file to the corresponding directory
                File file = createAttachedFileDir(attachedFile, dbName, runId, suiteId, testcaseId);
                fileItem.write(file);
                out.println("File uploaded to testcase " + testcaseId);
            } else {
                StringBuilder sb = new StringBuilder();
                if (StringUtils.isNullOrEmpty(attachedFile)) {
                    sb.append("Attached file name is null or empty!");
                    out.println(sb.toString());
                }
                if (StringUtils.isNullOrEmpty(dbName)) {
                    sb.append("Database name is null of empty!");
                    out.println(sb.toString());
                }
                if (runId <= 0) {
                    sb.append("RunId \"" + runId + "\" is not valid!");
                    out.println(sb.toString());
                }
                if (suiteId <= 0) {
                    sb.append("SuiteId \"" + suiteId + "\" is not valid!");
                    out.println(sb.toString());
                }
                if (testcaseId <= 0) {
                    sb.append("TestcaseId \"" + testcaseId + "\" is not valid!");
                    out.println(sb.toString());
                }
                response.sendError(HttpServletResponse.SC_CONFLICT, sb.toString());
                LOG.error("The file could not be attached to the test!");
            }
        } catch (Exception ex) {
            String errMsg = ex.getMessage();
            if (errMsg == null) {
                errMsg = ex.getClass().getSimpleName();
            }
            response.sendError(HttpServletResponse.SC_CONFLICT, ExceptionUtils.getExceptionMsg(ex));
            LOG.error("The file was unable to be attached to the testcase! ", ex);
        } finally {
            out.close();
        }
    }
}

From source file:edu.lafayette.metadb.web.projectman.CreateProject.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//w  w  w  .  j a  va  2s .c  o  m
 */
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    JSONObject output = new JSONObject();
    String delimiter = "";
    String projname = "";
    String projnotes = "";
    String template = "";
    boolean useTemplate = false;
    boolean disableQualifier = false;
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            Iterator it = fileItemsList.iterator();
            InputStream input = null;
            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                //MetaDbHelper.note("Field name: "+fileItem.getFieldName());
                //MetaDbHelper.note(fileItem.getString());
                if (fileItem.isFormField()) {
                    /*
                     * The file item contains a simple name-value pair of a
                     * form field
                     */
                    if (fileItem.getFieldName().equals("delimiter") && delimiter.equals(""))
                        delimiter = fileItem.getString();
                    else if (fileItem.getFieldName().equals("projname") && projname.equals(""))
                        projname = fileItem.getString().replace(" ", "_");
                    else if (fileItem.getFieldName().equals("projnotes") && projnotes.equals(""))
                        projnotes = fileItem.getString();
                    else if (fileItem.getFieldName().equals("project-template-checkbox"))
                        useTemplate = true;
                    else if (fileItem.getFieldName().equals("project-template"))
                        template = fileItem.getString().replace(" ", "_");
                    //else if (fileItem.getFieldName().equals("disable-qualifier-checkbox"))
                    //disableQualifier = true;
                } else
                    input = fileItem.getInputStream();

            }
            String userName = Global.METADB_USER;

            HttpSession session = request.getSession(false);
            if (session != null) {
                userName = (String) session.getAttribute(Global.SESSION_USERNAME);
            }

            //MetaDbHelper.note("Delimiter: "+delimiter+", projname: "+projname+", projnotes: "+projnotes+", use template or not? "+useTemplate+" template: "+template);
            if (useTemplate) {
                ProjectsDAO.createProject(template, projname, projnotes, "");
                output.put("projname", projname);
                output.put("success", true);
                output.put("message", "Project created successfully based on: " + template);
                SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                        "User created project " + projname + " with template from " + template);
            } else {
                if (ProjectsDAO.createProject(projname, projnotes)) {
                    output.put("projname", projname);
                    String delimiterType = "csv";
                    if (delimiter.equals("tab")) {
                        delimiterType = "tsv";
                        disableQualifier = true; // Disable text qualifiers for TSV files.
                    }
                    //MetaDbHelper.note("Delim: "+delimiterType+", projname: "+projname+", input: "+input);
                    if (input != null) {
                        Result res = DataImporter.importFile(delimiterType, projname, input, disableQualifier);
                        output.put("success", res.isSuccess());
                        if (res.isSuccess()) {
                            output.put("message", "Data import successfully");
                            SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                    "User created project " + projname + " with file import");
                        } else {

                            output.put("message", "The following fields have been changed");
                            SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                    "User created project " + projname + " with file import");
                            String fields = "";
                            ArrayList<String> data = (ArrayList<String>) res.getData();
                            for (String field : data)
                                fields += field + ',';
                            output.put("fields", fields);
                        }
                    } else {
                        output.put("success", true);
                        output.put("message",
                                "Project created successfully with default fields. No data imported");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User created project " + projname);
                    }
                } else {
                    output.put("success", false);
                    output.put("message", "Cannot create project");
                    SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User failed to create project " + projname);
                }
            }
        } else {
            output.put("success", false);
            output.put("message", "Form is not multi-part");
        }
    } catch (NullPointerException e) {
        try {
            output.put("success", true);
            output.put("message", "Project created successfully");
        } catch (JSONException e1) {
            MetaDbHelper.logEvent(e1);
        }

    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
        try {
            output.put("success", false);
            output.put("message", "Project was not created");
        } catch (JSONException e1) {
            MetaDbHelper.logEvent(e1);
        }
    }
    out.print(output);
    out.flush();

}

From source file:com.amalto.core.servlet.UploadFile.java

private void uploadFile(HttpServletRequest req, Writer writer) throws ServletException, IOException {
    // upload file
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new ServletException("Upload File Error: the request is not multipart!"); //$NON-NLS-1$
    }/*from www  . j ava  2 s .c  om*/
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();

    // Set upload parameters
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(0);
    upload.setFileItemFactory(factory);
    upload.setSizeMax(-1);

    // Parse the request
    List<FileItem> items;
    try {
        items = upload.parseRequest(req);
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }

    // Process the uploaded items
    if (items != null && items.size() > 0) {
        // Only one file
        Iterator<FileItem> iter = items.iterator();
        FileItem item = iter.next();
        if (LOG.isDebugEnabled()) {
            LOG.debug(item.getFieldName());
        }

        File file = null;
        if (!item.isFormField()) {
            try {
                String filename = item.getName();
                if (req.getParameter(PARAMETER_DEPLOY_JOB) != null) {
                    String contextStr = req.getParameter(PARAMETER_CONTEXT);
                    file = writeJobFile(item, filename, contextStr);
                } else if (filename.endsWith(".bar")) { //$NON-NLS-1$
                    file = writeWorkflowFile(item, filename);
                } else {
                    throw new IllegalArgumentException("Unknown deployment for file '" + filename + "'"); //$NON-NLS-1$ //$NON-NLS-2$
                }
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        } else {
            throw new ServletException("Couldn't process request"); //$NON-NLS-1$);
        }
        String urlRedirect = req.getParameter("urlRedirect"); //$NON-NLS-1$
        if (Boolean.valueOf(urlRedirect)) {
            String redirectUrl = req.getContextPath() + "?mimeFile=" + file.getName(); //$NON-NLS-1$
            writer.write(redirectUrl);
        } else {
            writer.write(file.getAbsolutePath());
        }
    }
    writer.close();
}

From source file:echopoint.tucana.UploadReceiverService.java

/**
 * @see BaseUploadService#service(nextapp.echo.webcontainer.Connection ,
 *      FileUploadSelector, String )/*w ww . j a  va 2  s . c  o  m*/
 */
public void service(final Connection conn, final FileUploadSelector uploadSelect, final String uploadIndex)
        throws IOException {
    final HttpServletRequest request = conn.getRequest();
    final ApplicationInstance app = conn.getUserInstance().getApplicationInstance();
    if (!ServletFileUpload.isMultipartContent(request)) {
        serviceBadRequest(conn, "Request must contain multipart content.");
        return;
    }

    final String contentLengthHeader = request.getHeader("Content-Length");
    final long contentLength;
    if (contentLengthHeader != null) {
        contentLength = Math.max(Long.parseLong(contentLengthHeader), -1);
    } else {
        contentLength = -1;
    }

    final UploadRenderState renderState = FileUploadSelectorPeer.getRenderState(uploadSelect,
            conn.getUserInstance());

    final UploadCallback callback = uploadSelect.getUploadCallback();
    final String fileName = ((callback != null) && (callback.getEvent() != null))
            ? callback.getEvent().getFileName()
            : null;
    try {
        final UploadProgress progress = new UploadProgress(contentLength);
        renderState.setProgress(uploadIndex, progress);
        renderState.uploadStarted(uploadIndex);

        UploadProviderFactory.getUploadProvider().handleUpload(conn, uploadSelect, uploadIndex, progress);
    } catch (IllegalStateException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(),
                new Cancel(uploadSelect, uploadIndex, fileName, contentLength, e));
    } catch (Exception e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new Fail(uploadSelect, uploadIndex, contentLength, e));
    } finally {
        renderState.uploadEnded(uploadIndex);
    }
}