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:com.arcadian.loginservlet.CourseContentServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }/*w ww  .  jav  a  2  s  .  co  m*/
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        String materialid = "";
        String materialname = "";
        String subjectid = "";
        String classname = "";
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            if (fileItem.isFormField()) {

                String name = fileItem.getFieldName();
                System.out.println(name);

                String value = fileItem.getString();
                System.out.println(value);

                if (name.equalsIgnoreCase("materialid")) {
                    materialid = value;
                }
                if (name.equalsIgnoreCase("materialname")) {
                    materialname = value;
                }
                if (name.equalsIgnoreCase("subjectid")) {
                    subjectid = value;
                }
                if (name.equalsIgnoreCase("semname")) {
                    classname = value;
                }

            }

            if (fileItem.getName() != null) {

                File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                        + fileItem.getName());
                System.out.println("Absolute Path at server=" + file.getAbsolutePath());
                fileItem.write(file);

                contentService = new CourseContentService();
                contentService.updatecoursematerial(materialid, materialname, classname, subjectid, username,
                        fileItem.getName());
            }
        }

    } catch (FileUploadException e) {
        System.out.println("Exception in file upload" + e);
    } catch (Exception ex) {
        Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    processRequest(request, response);

}

From source file:com.GTDF.server.FileUploadServlet.java

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

    String rootDirectory = getServletConfig().getInitParameter("TRANSFORM_HOME");
    String workDirectory = getServletConfig().getInitParameter("TRANSFORM_DIR");
    String prefixDirectory = "";
    boolean writeToFile = true;
    String returnOKMessage = "OK";
    String username = "";
    String authResult = "";

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    PrintWriter out = response.getWriter();

    // Create a factory for disk-based file items 
    if (isMultipart) {

        // We are uploading a file (deletes are performed by non multipart requests) 
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler 
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request 
        try {/*from w  ww  .j  av a2  s .  c o m*/

            List items = upload.parseRequest(request);

            // Process the uploaded items 
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {

                    // Hidden field containing username - check authorization
                    if (item.getFieldName().equals("username")) {
                        username = item.getString();
                        String wikiDb = getServletConfig().getInitParameter("WIKIDB");
                        String wikiDbUser = getServletConfig().getInitParameter("WIKIDB_USER");
                        String wikiDbPassword = getServletConfig().getInitParameter("WIKIDB_PASSWORD");
                        String wikiNoAuth = getServletConfig().getInitParameter("NOAUTH"); // v1.5 Check parameter NOAUTH
                        WikiUserImpl wikiUser = new WikiUserImpl();
                        authResult = wikiUser.wikiUserVerifyDb(username, wikiDb, wikiDbUser, wikiDbPassword,
                                wikiNoAuth);
                        if (authResult != "LOGGED") {
                            out.print(authResult);
                            return;
                        } else
                            new File(rootDirectory + workDirectory + '/' + username).mkdirs();
                    }

                    // Hidden field containing file prefix to create subdirectory
                    if (item.getFieldName().equals("prefix")) {
                        prefixDirectory = item.getString();
                        new File(rootDirectory + workDirectory + '/' + username + '/' + prefixDirectory)
                                .mkdirs();
                        prefixDirectory += '/';
                    }
                } else {
                    if (writeToFile) {
                        String fileName = item.getName();
                        if (fileName != null && !fileName.equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                            File uploadedFile = new File(rootDirectory + workDirectory + '/' + username + '/'
                                    + prefixDirectory + fileName);
                            try {
                                item.write(uploadedFile);
                                String hostedOn = getServletConfig().getInitParameter("HOSTED_ON");
                                out.print("Infile at: " + hostedOn + workDirectory + '/' + username + '/'
                                        + prefixDirectory + fileName);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    } else {

        //Process a request to delete a file 
        String[] paramValues = request.getParameterValues("uploadFormElement");
        for (int i = 0; i < paramValues.length; i++) {
            String fileName = FilenameUtils.getName(paramValues[i]);
            File deleteFile = new File(rootDirectory + workDirectory + fileName);
            if (deleteFile.delete()) {
                out.print(returnOKMessage);
            }
        }
    }

}

From source file:com.square.composant.envoi.email.square.server.servlet.UploadFichierServlet.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Cration d'un DiskFileItemFactory pour stocker les fichiers.
    if (isMultipart) {
        try {/*www.j  av a 2  s  . co m*/
            final FileItemFactory factory = new DiskFileItemFactory();
            final ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding(ComposantEnvoiEmailConstants.ENCODAGE_UTF_8);

            // Rcupration des items contenus dans la requte
            final List<FileItem> listeItems = upload.parseRequest(request);

            // Parcours des items
            for (FileItem item : listeItems) {

                // Fichier  uploader
                if (!item.isFormField()) {
                    // Nom du fichier
                    String nomFichier = "";
                    // on verifie si il y a un backslash
                    if (item.getName().indexOf("\\") != -1) {
                        // [\\\\] = expression rgulire pour dcouper suivant le backslash
                        final String[] tabNomFichier = item.getName().split("\\\\");
                        nomFichier = tabNomFichier[tabNomFichier.length - 1];
                    } else {
                        nomFichier = item.getName();
                    }

                    // Type MIME
                    final String typeMime = item.getContentType();

                    // Cration d'un fichier temporaire
                    String prefixe = nomFichier;
                    String suffixe = null;
                    if (nomFichier.indexOf(".") != -1) {
                        final int indexPoint = nomFichier.lastIndexOf(".");
                        prefixe = nomFichier.substring(0, indexPoint);
                        suffixe = nomFichier.substring(indexPoint);
                    }

                    if (prefixe.length() < 3) {
                        response.getOutputStream()
                                .print(ComposantEnvoiEmailConstants.ERREUR_UPLOAD_FICHIER_NOM_INCORRECT);
                    } else {
                        final File fichierTemporaire = File.createTempFile(prefixe, suffixe);
                        item.write(fichierTemporaire);

                        // Renvoi des infos concernant le fichier
                        final StringBuffer infosFichier = new StringBuffer();
                        infosFichier.append(ComposantEnvoiEmailConstants.PARAM_NOM_FICHIER)
                                .append(ComposantEnvoiEmailConstants.EGAL).append(nomFichier);
                        infosFichier.append(ComposantEnvoiEmailConstants.ET);
                        infosFichier.append(ComposantEnvoiEmailConstants.PARAM_PATH_FICHIER_TEMP)
                                .append(ComposantEnvoiEmailConstants.EGAL)
                                .append(fichierTemporaire.getCanonicalPath());
                        infosFichier.append(ComposantEnvoiEmailConstants.ET);
                        infosFichier.append(ComposantEnvoiEmailConstants.PARAM_TYPE_MIME)
                                .append(ComposantEnvoiEmailConstants.EGAL).append(typeMime);
                        response.getOutputStream().print(URLEncoder.encode(infosFichier.toString(),
                                ComposantEnvoiEmailConstants.ENCODAGE_UTF_8));
                    }
                }
            }

        } catch (FileUploadException e) {
            response.getOutputStream().print(ComposantEnvoiEmailConstants.ERREUR_UPLOAD_FICHIER);
        } catch (Exception e) {
            response.getOutputStream().print(ComposantEnvoiEmailConstants.ERREUR_UPLOAD_FICHIER);
        }
    }

}

From source file:commands.SendAnalysisRequest.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response, Controller controller) {
    //http://commons.apache.org/proper/commons-fileupload/using.html
    //process only if its multipart content
    String page = "Problem.jsp";
    if (ServletFileUpload.isMultipartContent(request)) {
        try {/*w ww .j a v  a 2 s.  c  om*/
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Configure a repository (to ensure a secure temp location is used)
            ServletContext servletContext = controller.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            System.out.println("File repository absolute path: " + repository.getAbsolutePath());

            factory.setRepository(repository);

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

            //parametros chave-valor (path valor)
            HashMap<String, String[]> params = new HashMap<String, String[]>();
            //parametros chave-valor para multimedia (path e array de bytes)
            HashMap<String, byte[]> mediaParams = new HashMap<String, byte[]>();

            // Tratando todos os parametros/itens da pagina (arquivos e no-arquivos)
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                //key (path)
                FileItem item = iter.next();
                String key = item.getFieldName();

                if (item.isFormField()) {
                    //printFormField(item);
                    //value
                    String[] value = new String[1];
                    value[0] = item.getString();
                    params.put(key, value);
                } else {
                    //printUploadedFile(item);
                    byte[] value = item.get();
                    mediaParams.put(key, value);
                }
            }

            //File uploaded successfully
            //              request.setAttribute("message", "File Uploaded Successfully");
            long result = new ParamedicController().sendAnalysisRequest(params, 1, mediaParams);

            if (result == -1) {
                request.setAttribute("message", "Occurred a problem to sending analysis request");
            } else {
                request.setAttribute("idAnalysis", result);
                request.setAttribute("message", "Analysis request sent successfully");
                page = "AnalysisResponseSearch.jsp";
                //RequestDispatcher reqDispatcher = request.getRequestDispatcher("AnalysisResponseSearch.jsp");
                //reqDispatcher.forward(request, response);
            }

            //                request.getRequestDispatcher("AnalysisResponseSearch.jsp").forward(request, response);
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
            ex.printStackTrace();
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
    try {
        request.getRequestDispatcher(page).forward(request, response);
    } catch (ServletException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.ephesoft.gxt.uploadbatch.server.UploadBatchImageServlet.java

private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService,
        String currentBatchUploadFolderName) throws IOException {

    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;//w w  w. j a v  a2 s  .c  o  m
    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;
                        while ((len = instream.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                    } catch (FileNotFoundException e) {
                        log.error("Unable to create the upload folder." + e, e);
                        printWriter.write("Unable to create the upload folder.Please try again.");
                        tempFile.delete();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "unable to upload. please see server logs for more details.");
                    } catch (IOException e) {
                        log.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                        tempFile.delete();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "unable to upload. please see server logs for more details.");
                    } 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.");
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "unable to upload. please see server logs for more details.");
        }

    } 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.silverpeas.gallery.servlets.GalleryDragAndDrop.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    SilverTrace.info("gallery", "GalleryDragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    String userId = null;/*from w ww  . j  a  va2s . com*/
    HttpRequest request = HttpRequest.decorate(req);
    try {
        request.setCharacterEncoding("UTF-8");
        String componentId = request.getParameter("ComponentId");
        String albumId = request.getParameter("AlbumId");
        userId = request.getParameter("UserId");
        SilverTrace.info("gallery", "GalleryDragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "componentId = " + componentId + " albumId = " + albumId + " userId = " + userId);
        String savePath = FileRepositoryManager.getTemporaryPath() + File.separatorChar + userId
                + System.currentTimeMillis() + File.separatorChar;
        List<FileItem> items = request.getFileItems();
        String parentPath = getParameterValue(items, "userfile_parent");
        SilverTrace.info("gallery", "GalleryDragAndDrop.doPost.doPost", "root.MSG_GEN_PARAM_VALUE",
                "parentPath = " + parentPath);

        SilverTrace.info("gallery", "GalleryDragAndDrop.doPost.doPost", "root.MSG_GEN_PARAM_VALUE",
                "debut de la boucle");
        for (FileItem item : items) {
            if (!item.isFormField()) {
                String fileName = FileUploadUtil.getFileName(item);
                SilverTrace.info("gallery", "GalleryDragAndDrop.doPost.doPost", "root.MSG_GEN_PARAM_VALUE",
                        "item = " + item.getFieldName() + " - " + fileName);
                if (fileName != null) {
                    SilverTrace.info("gallery", "GalleryDragAndDrop.doPost.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "fileName = " + fileName);
                    // modifier le nom avant de l'crire
                    File f = new File(savePath + File.separatorChar + fileName);
                    File parent = f.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    item.write(f);
                    // Cas du zip
                    if (FileUtil.isArchive(fileName)) {
                        ZipManager.extract(f, parent);
                    }
                }
            }
        }
        importRepository(new File(savePath), userId, componentId, albumId);
        FileFolderManager.deleteFolder(savePath);
    } catch (Exception e) {
        SilverTrace.debug("gallery", "GalleryDragAndDrop.doPost.doPost", "root.MSG_GEN_PARAM_VALUE", e);
        final StringBuilder sb = new StringBuilder("ERROR");
        final String errorMessage = SilverpeasTransverseWebErrorUtil.performAppletAlertExceptionMessage(e,
                UserDetail.getById(userId).getUserPreferences().getLanguage());
        if (isDefined(errorMessage)) {
            sb.append(": ");
            sb.append(errorMessage);
        }
        res.getOutputStream().println(sb.toString());
    }
    res.getOutputStream().println("SUCCESS");
}

From source file:com.skin.taurus.http.servlet.UploadServlet.java

public void upload(HttpRequest request, HttpResponse response) throws IOException {
    int maxFileSize = 1024 * 1024;
    String repository = System.getProperty("java.io.tmpdir");
    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setRepository(new File(repository));
    factory.setSizeThreshold(maxFileSize * 2);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

    servletFileUpload.setFileSizeMax(maxFileSize);
    servletFileUpload.setSizeMax(maxFileSize);

    try {// w  w  w  .  j  a v  a 2 s.c  om
        HttpServletRequest httpRequest = new HttpServletRequestAdapter(request);
        List<?> list = servletFileUpload.parseRequest(httpRequest);

        for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
            FileItem item = (FileItem) iterator.next();

            if (item.isFormField()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Form Field: " + item.getFieldName() + " " + item.toString());
                }
            } else if (!item.isFormField()) {
                if (item.getFieldName() != null) {
                    String fileName = this.getFileName(item.getName());
                    String extension = this.getFileExtensionName(fileName);

                    if (this.isAllowed(extension)) {
                        try {
                            this.save(item);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    item.delete();
                } else {
                    item.delete();
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.FileUploadServlet.java

/**
 * Processes requests for both HTTP//from www .  j ava  2s  . c  om
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    log("isMultipartContent: " + isMultiPart);
    log("Content-Type: " + request.getContentType());
    if (isMultiPart) {

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

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

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

        // Parse the request
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        PrintWriter out = response.getWriter();
        out.print("<html><head><title>SUCCESS</title></head><body><h1>DONE!</h1>");

        ListIterator li = items.listIterator();
        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                processFormField(fileItem);
            } else {
                out.append(processUploadedFile(fileItem));
            }
        }
        out.print("</body></html>");
        out.flush();
        out.close();

    }
}

From source file:net.morphbank.mbsvc3.webservices.RestServiceExcelUpload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ArrayList<String> reportContent = new ArrayList<String>();
    response.setContentType("text/xml");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {/*from  www  .  j ava2s.c  o  m*/
        // Process the uploaded items
        List<?> /* FileItem */ items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                // processFormField(item);
            } else {
                String report = this.processUploadedFile(item);
                reportContent = this.outputReport(report, reportContent);
                htmlPresentation(request, response, folderPath, reportContent);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

}

From source file:Controller.ControllerProducts.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  w w.ja v  a  2 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);
                    System.out.println("path" + fileName);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    System.out.println("Rpath" + RealPath);
                    File savedFile = new File(RealPath);
                    item.write(savedFile);
                    //System.out.println("upload\\"+fileName);
                    //insert Product
                    String code = (String) params.get("txtcode");
                    String name = (String) params.get("txtname");
                    String price = (String) params.get("txtprice");
                    Products sp = new Products();
                    sp.InsertProduct(code, name, price, "upload\\" + fileName);
                    RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }
    //this.processRequest(request, response);
}