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

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

Introduction

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

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:adminpackage.adminview.UpdateProductServlet.java

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

    String value = "defa";
    AdminUpdateProductWrapper product = new AdminUpdateProductWrapper();

    try {/*from   www . j av  a  2 s .com*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        String url = "";
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                value = item.getString();
                switch (name) {
                case "pid":
                    product.setId(Integer.parseInt(value));
                    break;
                case "pname":
                    product.setName(value);
                    break;
                case "quantity":
                    product.setQuantity(Integer.parseInt(value));
                    break;
                case "author":
                    product.setAuthor(value);
                    break;
                case "isbn":
                    product.setISBN(Long.parseLong(value));
                    break;
                case "description":
                    product.setDescription(value);
                    break;
                case "category":
                    product.setCategory(value);
                    break;
                case "price":
                    product.setPrice(Integer.parseInt(value));
                    break;
                }
            } else {

                try {
                    if (item.getName().length() > 0) {
                        item.write(new File(context.getRealPath("/pages/images/").replaceAll(
                                "\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp")
                                + item.getName()));
                        //System.out.println(context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName());
                        //url = context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName();
                        UUID idOne = UUID.randomUUID();
                        product.setImage(
                                idOne.toString() + item.getName().substring(item.getName().length() - 4));
                    }
                } catch (Exception ex) {
                    Logger.getLogger(UpdateProductServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    } catch (FileUploadException ex) {
        Logger.getLogger(UpdateProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("adminpackage.adminview.UpdateProductServlet.processRequest()");
    out.print(adminFacadeHandler.UpdateProduct(product));
    if (value != null) {

    }

}

From source file:br.com.ecommkw.rest.UploadFile.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/* www. j  a va2s. c  o m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

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

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

        try {
            // Parse the request
            @SuppressWarnings("rawtypes")
            List /* FileItem */ items = upload.parseRequest(request);
            @SuppressWarnings("rawtypes")
            Iterator iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String root = getServletContext().getRealPath("/");
                    File path = new File(root + "/pics");
                    if (!path.exists()) {
                        @SuppressWarnings("unused")
                        boolean status = path.mkdirs();
                    }

                    File uploadedFile = new File(path + "/" + fileName);
                    System.out.println(uploadedFile.getAbsolutePath());
                    item.write(uploadedFile);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.MultipartHttpServletRequest.java

/** Minimize the code that uses the unchecked cast. */
@SuppressWarnings("unchecked")
private List<FileItem> parseRequestIntoFileItems(HttpServletRequest req, ServletFileUpload upload)
        throws FileUploadException {
    return upload.parseRequest(req);
}

From source file:it.unisa.tirocinio.servlet.studentUploadFiles.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w w  . j a v a  2  s  . c o  m
 *
 * @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");
    response.setHeader("Access-Control-Allow-Origin", "*");
    PrintWriter out = response.getWriter();
    HttpSession aSession = request.getSession();
    try {
        Person pers = (Person) aSession.getAttribute("person");
        String primaryKey = pers.getAccount().getEmail();
        PersonManager aPerson = PersonManager.getInstance();
        Person person = aPerson.getStudent(primaryKey);
        ConcreteStudentInformation aStudentInformation = ConcreteStudentInformation.getInstance();
        out = response.getWriter();

        String studentSubfolderPath = filePath + "/" + reverseSerialNumber(person.getMatricula());
        File subfolderFile = new File(studentSubfolderPath);
        if (!subfolderFile.exists()) {
            subfolderFile.mkdir();
        }

        isMultipart = ServletFileUpload.isMultipartContent(request);
        String serialNumber = null;
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        File fileToStore = null;
        String CVPath = "", ATPath = "";

        while (i.hasNext()) {

            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                if (fieldName.equals("cv")) {
                    fileToStore = new File(studentSubfolderPath + "/" + "CV.pdf");
                    CVPath = fileToStore.getAbsolutePath();
                } else if (fieldName.equals("doc")) {
                    fileToStore = new File(studentSubfolderPath + "/" + "ES.pdf");
                    ATPath = fileToStore.getAbsolutePath();
                }
                fi.write(fileToStore);

                // out.println("Uploaded Filename: " + fieldName + "<br>");
            } else {
                //out.println("It's not formfield");
                //out.println(fi.getString());

            }

        }

        if (aStudentInformation.startTrainingRequest(person.getSsn(), CVPath, ATPath)) {
            message.setMessage("status", 1);
        } else {
            message.setMessage("status", 0);
        }
        aSession.setAttribute("message", message);
        response.sendRedirect(request.getContextPath() + "/tirocinio/studente/tprichiestatirocinio.jsp");
        //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tirocinio/studente/tprichiestatirocinio.jsp");
        //dispatcher.forward(request,response);
    } catch (Exception ex) {
        Logger.getLogger(studentUploadFiles.class.getName()).log(Level.SEVERE, null, ex);
        message.setMessage("status", -1);
        aSession.setAttribute("message", message);
    } finally {
        out.close();
    }
}

From source file:be.fedict.eid.dss.sp.servlet.UploadServlet.java

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

    LOG.debug("doPost");

    String fileName = null;//from w w w.  j  a  va2  s.c  om
    String contentType;
    byte[] document = null;

    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        if (!items.isEmpty()) {
            fileName = items.get(0).getName();
            // contentType = items.get(0).getContentType();
            document = items.get(0).get();
        }
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    String extension = FilenameUtils.getExtension(fileName).toLowerCase();
    contentType = supportedFileExtensions.get(extension);
    if (null == contentType) {
        /*
         * Unsupported content-type is converted to a ZIP container.
         */
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.write(document, zipOutputStream);
        zipOutputStream.close();
        fileName = FilenameUtils.getBaseName(fileName) + ".zip";
        document = outputStream.toByteArray();
        contentType = "application/zip";
    }

    LOG.debug("File name: " + fileName);
    LOG.debug("Content Type: " + contentType);

    String signatureRequest = new String(Base64.encode(document));

    request.getSession().setAttribute(DOCUMENT_SESSION_ATTRIBUTE, document);
    request.getSession().setAttribute("SignatureRequest", signatureRequest);
    request.getSession().setAttribute("ContentType", contentType);

    response.sendRedirect(request.getContextPath() + this.postPage);
}

From source file:br.univali.celine.lms.utils.MultipartRequestProcessor.java

public void processRequest(HttpServletRequest request) {

    try {/*from   ww w  .java  2 s .c  om*/

        parameters = new HashMap<String, Object>();
        files = new ArrayList<FileItem>();

        DiskFileItemFactory dfif = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(dfif);

        upload.setProgressListener(progressListener);
        List<?> items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();

        while (iter.hasNext()) {

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

            if (item.isFormField())
                parameters.put(item.getFieldName(), item.getString());

            else
                files.add(item);
        }

    } catch (Exception e) {

        LMSLogger.throwing(e);

    }

}

From source file:check_reg_bidder.java

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

    try {/*from w  w w . jav a 2 s .  com*/

        HttpSession sess = request.getSession(true);
        String f = (String) sess.getAttribute("fn");
        String l = (String) sess.getAttribute("ln");
        String mail = (String) sess.getAttribute("em");
        String un = (String) sess.getAttribute("usr");
        String pwd = (String) sess.getAttribute("pass");
        String add = (String) sess.getAttribute("add");
        String phn = (String) sess.getAttribute("no");
        String cit = (String) sess.getAttribute("city");
        String ut = (String) sess.getAttribute("type");
        String des = (String) sess.getAttribute("des");
        String dept = (String) sess.getAttribute("depa");

        //            out.println(dept);

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/project?zeroDateTimeBehavior=convertToNull", "root", "root");
        Statement st = con.createStatement();

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);//retrive req.. data & extract below
        //out.println(isMultipart);
        if (isMultipart) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            String paraname[] = new String[15];
            int i = 0;
            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {
                org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) iterator
                        .next();
                paraname[i] = item.getString();// one by one tag's values to arrat

                //out.println(i+"----"+paraname[i]);
                //out.println("<br>");
                i++;
                if (!item.isFormField())// if type=file
                {
                    String fileName = item.getName();// uploadiing file
                    out.println(fileName);
                    String root = "D:\\rushiraj\\Main Project\\web";//currnet path
                    File path = new File(root + "/cmpfile");// path plus testimage directory
                    if (!path.exists()) {
                        boolean status = path.mkdirs(); //if dir! not exists than createe once
                    }
                    File uploadedFile = new File(path + "/" + fileName); /// upload file/image  at path

                    item.write(uploadedFile);//phiscaly write-
                    String q1 = "insert into company_details (name,pan_no,it_cer,est_date,lic_val,reg_no,address,city,state,class) values('"
                            + paraname[0] + "','" + paraname[1] + "','" + fileName + "','" + paraname[2] + "','"
                            + paraname[3] + "','" + paraname[4] + "','" + paraname[5] + paraname[6]
                            + paraname[7] + "','" + paraname[8] + "','" + paraname[9] + "','" + paraname[10]
                            + "')";
                    String query = "insert into register (first_name,last_name,mail,username,password,phone,address,city,type,designation,department) values('"
                            + f + "','" + l + "','" + mail + "','" + un + "','" + pwd + "','" + phn + "','"
                            + add + "','" + cit + "','" + ut + "','" + des + "','" + dept + "');";
                    out.println(q1);
                    out.println(query);
                    int r = st.executeUpdate(q1);//insert remaing data into table.....
                    int p = st.executeUpdate(query);

                    if (r > 0) {
                        response.sendRedirect("login.jsp");
                    }
                }
            }
        }
    } catch (Exception ex) {
        out.println(ex);
    }

}

From source file:by.creepid.jsf.fileupload.UploadFilter.java

@SuppressWarnings("unchecked")
@Override/*from  w w  w . j a v  a 2 s  .c  o m*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if ((request instanceof HttpServletRequest)) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        if (ServletFileUpload.isMultipartContent(httpRequest)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setRepository(new File(repositoryPath));

            ServletFileUpload upload = new ServletFileUpload(factory);

            try {

                List<FileItem> items = (List<FileItem>) upload.parseRequest(httpRequest);
                final Map<String, String[]> map = new HashMap<String, String[]>();

                for (FileItem item : items) {
                    if (item.isFormField()) {
                        processFormField(item, map);
                    } else {
                        processFileField(item, httpRequest);
                    }
                }

                request = UploadFilter.wrapRequest(httpRequest, map);

            } catch (FileUploadException ex) {
                throw new ServletException(ex);
            }
        }
    }
    chain.doFilter(request, response);
}

From source file:com.martin.zkedit.controller.Import.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Importing Action!");
    try {/*from w  ww  .  j  av a2  s.  c  o  m*/
        Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps");
        Dao dao = new Dao(globalProps);
        String zkServer = globalProps.getProperty("zkServer");
        String[] zkServerLst = zkServer.split(",");

        StringBuilder sbFile = new StringBuilder();
        String scmOverwrite = "false";
        String scmServer = "";
        String scmFilePath = "";
        String scmFileRevision = "";
        String uploadFileName = "";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1034);
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = upload.parseRequest(request);

        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                if (item.getFieldName().equals("scmOverwrite")) {
                    scmOverwrite = item.getString();
                }
                if (item.getFieldName().equals("scmServer")) {
                    scmServer = item.getString();
                }
                if (item.getFieldName().equals("scmFilePath")) {
                    scmFilePath = item.getString();
                }
                if (item.getFieldName().equals("scmFileRevision")) {
                    scmFileRevision = item.getString();
                }

            } else {
                uploadFileName = item.getName();
                sbFile.append(item.getString());
            }
        }

        InputStream inpStream;

        if (sbFile.toString().length() == 0) {
            uploadFileName = scmServer + scmFileRevision + "@" + scmFilePath;
            logger.debug("P4 file Processing " + uploadFileName);
            dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(),
                    "Importing P4 File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite);
            URL url = new URL(uploadFileName);
            URLConnection conn = url.openConnection();
            inpStream = conn.getInputStream();

        } else {
            logger.debug("Upload file Processing " + uploadFileName);
            dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(),
                    "Uploading File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite);
            inpStream = new ByteArrayInputStream(sbFile.toString().getBytes());
        }

        // open the stream and put it into BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(inpStream));
        String inputLine;
        List<String> importFile = new ArrayList<>();
        Integer lineCnt = 0;
        while ((inputLine = br.readLine()) != null) {
            lineCnt++;
            // Empty or comment?
            if (inputLine.trim().equals("") || inputLine.trim().startsWith("#")) {
                continue;
            }
            if (inputLine.startsWith("-")) {
                //DO nothing.
            } else if (!inputLine.matches("/.+=.+=.*")) {
                throw new IOException("Invalid format at line " + lineCnt + ": " + inputLine);
            }

            importFile.add(inputLine);
        }
        br.close();

        ZooKeeperUtil.INSTANCE.importData(importFile, Boolean.valueOf(scmOverwrite),
                ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0]));
        for (String line : importFile) {
            if (line.startsWith("-")) {
                dao.insertHistory((String) request.getSession().getAttribute("authName"),
                        request.getRemoteAddr(), "File: " + uploadFileName + ", Deleting Entry: " + line);
            } else {
                dao.insertHistory((String) request.getSession().getAttribute("authName"),
                        request.getRemoteAddr(), "File: " + uploadFileName + ", Adding Entry: " + line);
            }
        }
        request.getSession().setAttribute("flashMsg", "Import Completed!");
        response.sendRedirect("/home");
    } catch (FileUploadException | IOException | InterruptedException | KeeperException ex) {
        ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
    }
}

From source file:com.deem.zkui.controller.Import.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Importing Action!");
    try {/* ww  w .j  a va2s .  co  m*/
        Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps");
        Dao dao = new Dao(globalProps);
        String zkServer = globalProps.getProperty("zkServer");
        String[] zkServerLst = zkServer.split(",");

        StringBuilder sbFile = new StringBuilder();
        String scmOverwrite = "false";
        String scmServer = "";
        String scmFilePath = "";
        String scmFileRevision = "";
        String uploadFileName = "";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1034);
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = upload.parseRequest(request);

        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                if (item.getFieldName().equals("scmOverwrite")) {
                    scmOverwrite = item.getString();
                }
                if (item.getFieldName().equals("scmServer")) {
                    scmServer = item.getString();
                }
                if (item.getFieldName().equals("scmFilePath")) {
                    scmFilePath = item.getString();
                }
                if (item.getFieldName().equals("scmFileRevision")) {
                    scmFileRevision = item.getString();
                }

            } else {
                uploadFileName = item.getName();
                sbFile.append(item.getString());
            }
        }

        InputStream inpStream;

        if (sbFile.toString().length() == 0) {
            uploadFileName = scmServer + scmFileRevision + "@" + scmFilePath;
            logger.debug("P4 file Processing " + uploadFileName);
            dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(),
                    "Importing P4 File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite);
            URL url = new URL(uploadFileName);
            URLConnection conn = url.openConnection();
            inpStream = conn.getInputStream();

        } else {
            logger.debug("Upload file Processing " + uploadFileName);
            dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(),
                    "Uploading File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite);
            inpStream = new ByteArrayInputStream(sbFile.toString().getBytes());
        }

        // open the stream and put it into BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(inpStream));
        String inputLine;
        List<String> importFile = new ArrayList<>();
        Integer lineCnt = 0;
        while ((inputLine = br.readLine()) != null) {
            lineCnt++;
            // Empty or comment?
            if (inputLine.trim().equals("") || inputLine.trim().startsWith("#")) {
                continue;
            }
            if (inputLine.startsWith("-")) {
                //DO nothing.
            } else if (!inputLine.matches("/.+=.+=.*")) {
                throw new IOException("Invalid format at line " + lineCnt + ": " + inputLine);
            }

            importFile.add(inputLine);
        }
        br.close();

        ZooKeeperUtil.INSTANCE.importData(importFile, Boolean.valueOf(scmOverwrite),
                ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps));
        for (String line : importFile) {
            if (line.startsWith("-")) {
                dao.insertHistory((String) request.getSession().getAttribute("authName"),
                        request.getRemoteAddr(), "File: " + uploadFileName + ", Deleting Entry: " + line);
            } else {
                dao.insertHistory((String) request.getSession().getAttribute("authName"),
                        request.getRemoteAddr(), "File: " + uploadFileName + ", Adding Entry: " + line);
            }
        }
        request.getSession().setAttribute("flashMsg", "Import Completed!");
        response.sendRedirect("/home");
    } catch (FileUploadException | IOException | InterruptedException | KeeperException ex) {
        logger.error(Arrays.toString(ex.getStackTrace()));
        ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
    }
}