Example usage for org.apache.commons.fileupload DiskFileUpload parseRequest

List of usage examples for org.apache.commons.fileupload DiskFileUpload parseRequest

Introduction

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

Prototype

public List  parseRequest(HttpServletRequest req) 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:com.pureinfo.srm.RequestUtils.java

public static PureProperties parse(HttpServletRequest _request) throws PureException {
    logger.debug("enti");
    PureProperties props = new PureProperties();

    Enumeration names = _request.getParameterNames();
    logger.debug("enti11111111111#" + names.hasMoreElements());
    while (names.hasMoreElements()) {
        String sName = (String) names.nextElement();
        String[] values = _request.getParameterValues(sName);
        if (values.length == 1) {
            props.setProperty(sName, values[0]);
        } else {//  ww  w.j  av a 2 s .  co  m
            props.setProperty(sName, values);
        }

    }

    String sContentType = _request.getContentType();
    if (sContentType != null && sContentType.startsWith("multipart/form-data")) {
        logger.debug("enti111");
        DiskFileUpload upload = new DiskFileUpload();
        List items;
        try {
            items = upload.parseRequest(_request);
        } catch (FileUploadException ex) {
            throw new PureException(PureException.UNKNOWN, "upload error", ex);
        }
        logger.debug("enti111111111111" + items.size());
        for (Iterator iter = items.iterator(); iter.hasNext();) {
            FileItem item = (FileItem) iter.next();
            if (item.getName() == null) {
                props.setProperty(item.getFieldName(), item.getString());
            } else {
                props.setProperty(item.getFieldName(), item);
            }
            logger.debug("name:" + item.getFieldName() + "-value:" + props.getProperty(item.getFieldName()));
        }
    }

    return props;
}

From source file:com.krawler.esp.handlers.fileUploader.java

public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam,
        ArrayList<FileItem> fi, boolean fileUpload) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;/*from   w w w. ja  v  a2  s . c o m*/
    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createUser", e);
    }
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        if (fi1.isFormField()) {
            arrParam.put(fi1.getFieldName(), fi1.getString());
        } else {
            try {
                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    fileUpload = true;
                }
            } catch (UnsupportedEncodingException ex) {
            }
        }
    }
}

From source file:com.krawler.esp.handlers.fileUploader.java

public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam,
        ArrayList<FileItem> fi, boolean fileUpload, HashMap<Integer, String> filemap) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;//from  w w  w.  j  a  v  a 2s .  c om
    List fileItems = null;
    int i = 0;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createUser", e);
    }
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        try {
            if (fi1.isFormField()) {
                arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
            } else {

                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    filemap.put(i, fi1.getFieldName());
                    i++;
                    fileUpload = true;
                }
            }
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.krawler.esp.servlets.SuperAdminServlet.java

public static String editCompany(Connection conn, HttpServletRequest request, HttpServletResponse response)
        throws ServiceException {

    String status = "";
    DiskFileUpload fu = new DiskFileUpload();
    JSONObject j = new JSONObject();
    JSONObject j1 = new JSONObject();
    List fileItems = null;/*www  .j a  va  2s  . c o m*/
    FileItem fi1 = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("SuperAdminHandler.editCompany", e);
    }

    HashMap arrParam = new HashMap();
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        arrParam.put(fi1.getFieldName(), fi1.getString());
    }
    try {
        DbUtil.executeUpdate(conn,
                "update company set companyname=?, address=?, city=?, state=?, country=?, phone=?, fax=?, "
                        + "zip=?, timezone=?, website=? where companyid=?;",
                new Object[] { arrParam.get("companyname"), arrParam.get("address"), arrParam.get("city"),
                        arrParam.get("state"), arrParam.get("country"), arrParam.get("phone"),
                        arrParam.get("fax"), arrParam.get("zip"), arrParam.get("timezone"),
                        arrParam.get("website"), arrParam.get("companyid") });
        j.put("companyname", arrParam.get("companyname"));
        j.put("address", arrParam.get("address"));
        j.put("city", arrParam.get("city"));
        j.put("state", arrParam.get("state"));
        j.put("country", arrParam.get("country"));
        j.put("phone", arrParam.get("phone"));
        j.put("fax", arrParam.get("fax"));
        j.put("zip", arrParam.get("zip"));
        j.put("timezone", arrParam.get("timezone"));
        j.put("website", arrParam.get("website"));
        j.put("companyid", arrParam.get("companyid"));
        if (arrParam.get("image").toString().length() != 0) {
            genericFileUpload uploader = new genericFileUpload();
            try {
                uploader.doPost(fileItems, arrParam.get("companyid").toString(),
                        StorageHandler.GetProfileImgStorePath());
            } catch (ConfigurationException e) {
                throw ServiceException.FAILURE("SuperAdminHandler.createCompany", e);
            }
            if (uploader.isUploaded()) {
                DbUtil.executeUpdate(conn, "update company set image=? where companyid = ?",
                        new Object[] { ProfileImageServlet.ImgBasePath + arrParam.get("companyid").toString()
                                + uploader.getExt(), arrParam.get("companyid") });
                j.put("image", arrParam.get("companyid") + uploader.getExt());
            }
        }
        j1.append("data", j);
        status = j1.toString();
    } catch (JSONException e) {
        status = "failure";
        throw ServiceException.FAILURE("SuperAdminHandler.editCompany", e);
    }
    return status;
}

From source file:com.krawler.esp.servlets.SuperAdminServlet.java

public static String createCompany(Connection conn, HttpServletRequest request, HttpServletResponse response)
        throws ServiceException {
    String status = "";
    DiskFileUpload fu = new DiskFileUpload();
    ResultSet frs = null, ars = null;
    PreparedStatement pstmt = null, fpstmt = null, apstmt = null;
    double val = 0.0;
    List fileItems = null;/*  w  w w. ja  va2 s  .co m*/
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("SuperAdminHandler.createCompany", e);
    }

    HashMap arrParam = new HashMap();
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        FileItem fi1 = (FileItem) k.next();
        arrParam.put(fi1.getFieldName(), fi1.getString());
    }
    String companyid = UUID.randomUUID().toString();
    /*DbUtil
    .executeUpdate(
          conn,
          "insert into company(companyid, companyname, createdon, address, city, state, country, phone, fax, zip, "
                + "timezone, website) values (?, ?, now(), ?, ?, ?, ?, ?, ?, ?, ?, ?);",
          new Object[] { companyid, arrParam.get("companyname"),
                arrParam.get("address"), arrParam.get("city"),
                arrParam.get("state"), arrParam.get("country"),
                arrParam.get("phone"), arrParam.get("fax"),
                arrParam.get("zip"), arrParam.get("timezone"),
                arrParam.get("website") });*/
    java.util.Date d = new java.util.Date();
    java.sql.Timestamp today = new Timestamp(d.getTime());
    DbUtil.executeUpdate(conn,
            "INSERT INTO company(companyid, companyname, address, createdon, website) values (?,?,?,?,?);",
            new Object[] { companyid, arrParam.get("companyname"), arrParam.get("address"), today,
                    arrParam.get("website") });
    String userid = UUID.randomUUID().toString();
    String newPass = AuthHandler.generateNewPassword();
    String newPassSHA1 = AuthHandler.getSHA1(newPass);
    DbUtil.executeUpdate(conn, "insert into userlogin(userid, username, password, authkey) values (?,?,?,?);",
            new Object[] { userid, arrParam.get("username"), newPassSHA1, newPass });
    DbUtil.executeUpdate(conn, "insert into users(userid, companyid, image) values (?,?,?);",
            new Object[] { userid, companyid, "" });
    try {
        fpstmt = conn.prepareStatement("SELECT featureid FROM featurelist");
        frs = fpstmt.executeQuery();
        while (frs.next()) {
            apstmt = conn.prepareStatement("SELECT activityid FROM activitieslist WHERE featureid=?");
            apstmt.setInt(1, frs.getInt("featureid"));
            ars = apstmt.executeQuery();
            while (ars.next()) {
                val += Math.pow(2, Double.parseDouble(ars.getString("activityid")));
            }
            pstmt = conn.prepareStatement(
                    "INSERT INTO userpermissions (userid, featureid, permissions) VALUES (?,?,?)");
            pstmt.setString(1, userid);
            pstmt.setInt(2, frs.getInt("featureid"));
            pstmt.setInt(3, (int) val);
            pstmt.executeUpdate();

            val = 0.0;
        }
    } catch (SQLException e) {
        throw ServiceException.FAILURE("signup.confirmSignup", e);
    } finally {
        DbPool.closeStatement(pstmt);
    }
    if (arrParam.get("image").toString().length() != 0) {
        genericFileUpload uploader = new genericFileUpload();
        try {
            uploader.doPost(fileItems, companyid, StorageHandler.GetProfileImgStorePath());
        } catch (ConfigurationException e) {
            throw ServiceException.FAILURE("SuperAdminHandler.createCompany", e);
        }
        if (uploader.isUploaded()) {
            DbUtil.executeUpdate(conn, "update company set image=? where companyid = ?", new Object[] {
                    ProfileImageServlet.ImgBasePath + companyid + uploader.getExt(), companyid, companyid });
        }
    }
    status = "success";
    return status;
}

From source file:com.krawler.esp.servlets.importToDoTask.java

public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException {
    String result = "";
    try {/*from ww w.j  a  va  2 s.  c o  m*/
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importplans";
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }

        long size = 0;
        String Ext = "";
        String fileName = null;
        boolean fileupload = false;
        java.io.File destDir = new java.io.File(destinationDirectory);
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        java.util.HashMap arrParam = new java.util.HashMap();
        for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
            fi = (org.apache.commons.fileupload.FileItem) k.next();
            arrParam.put(fi.getFieldName(), fi.getString());
            if (!fi.isFormField()) {
                size = fi.getSize();
                fileName = new String(fi.getName().getBytes(), "UTF8");

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
            }
            if (size != 0) {
                File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);
                result = fileid + Ext;
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    }
    return result;
}

From source file:com.krawler.esp.handlers.basecampHandler.java

public static File getfile(HttpServletRequest request, String docid) throws ConfigurationException {
    String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
            + "baseCamxml";
    java.io.File destDir = new java.io.File(destinationDirectory);

    if (!destDir.exists()) {
        destDir.mkdirs();//from w  w  w. j a  v  a 2 s  .c  om
    }
    DiskFileUpload fu = new DiskFileUpload();
    String Ext = null;
    File uploadFile = null;
    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
    }
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
            String fileName = null;
            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                if (fileName.contains(".")) {
                    Ext = fileName.substring(fileName.lastIndexOf("."));
                }
                if (fi.getSize() != 0) {
                    uploadFile = new File(
                            destinationDirectory + StorageHandler.GetFileSeparator() + docid + ".xml");
                    fi.write(uploadFile);
                }
            } catch (Exception e) {
                KrawlerLog.op.warn("Problem While Reading file :" + e.toString());
            }
        }
    }

    return uploadFile;
}

From source file:com.krawler.esp.servlets.ExportImportContactsServlet.java

public static String uploadDocument(HttpServletRequest request, String fileid, String userId)
        throws ServiceException {
    String result = "";
    try {/*  w w  w .  j a v  a 2s.  c om*/
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importcontacts" + StorageHandler.GetFileSeparator() + userId;
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }

        long size = 0;
        String Ext = "";
        String fileName = null;
        boolean fileupload = false;
        java.io.File destDir = new java.io.File(destinationDirectory);
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        java.util.HashMap arrParam = new java.util.HashMap();
        for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
            fi = (org.apache.commons.fileupload.FileItem) k.next();
            arrParam.put(fi.getFieldName(), fi.getString());
            if (!fi.isFormField()) {
                size = fi.getSize();
                fileName = new String(fi.getName().getBytes(), "UTF8");

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
            }
            if (size != 0) {
                File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);
                result = fileid + Ext;
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("ExportImportContactServlet.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("ExportImportContactServlet.uploadDocument", ex);
    }
    return result;
}

From source file:productsave.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {//from w ww .java  2 s  .  co m
        ServletContext x = this.getServletContext();
        String path = x.getRealPath("/images");

        System.out.println(path + " path");
        DiskFileUpload p = new DiskFileUpload();
        List q = p.parseRequest(request);
        Iterator z = q.iterator();
        while (z.hasNext()) {
            FileItem f = (FileItem) z.next();
            if (f.isFormField() == true) {
                //non-file data
                System.out.println("executed");
                String h = f.getFieldName();
                String data = f.getString();
                if (h.equalsIgnoreCase("productname")) {
                    productname = data;
                } else if (h.equalsIgnoreCase("category")) {
                    categoryid = data;
                    System.out.println(categoryid + " cccc");
                } else if (h.equalsIgnoreCase("price")) {
                    price = data;
                } else if (h.equalsIgnoreCase("description")) {
                    description = data;
                }

            } else {
                //file data
                String filename = f.getName();
                if (filename != null && filename.length() > 0) {
                    File g = new File(filename);

                    filename = g.getName();

                    //creating unique file name
                    long w = System.currentTimeMillis();
                    filename = w + filename;
                    System.out.println("path " + path + " file " + filename);
                    //upload file
                    File t = new File(path, filename);
                    f.write(t);
                    if (f.getFieldName().equals("image")) {
                        image = filename;
                    }
                }

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

    productbean product = new productbean();
    product.setProductname(productname);
    product.setCategoryid(categoryid);
    product.setDescription(description);
    product.setImage(image);
    product.setPrice(price);
    int count = product.save();
    if (count != 0) {
        out.println("1");
    } else {
        out.println("0");
    }
}

From source file:productupdate.java

void getformdata() {
    try {// w  w w  . ja v a  2s.co  m
        ServletContext x = this.getServletContext();
        String path = x.getRealPath("/images");

        System.out.println(path + " path");
        DiskFileUpload p = new DiskFileUpload();
        List q = p.parseRequest(request);
        Iterator z = q.iterator();
        while (z.hasNext()) {
            FileItem f = (FileItem) z.next();
            if (f.isFormField() == true) {
                //non-file data

                String h = f.getFieldName();
                String data = f.getString();
                if (h.equalsIgnoreCase("productid")) {
                    productid = data;
                } else if (h.equalsIgnoreCase("productname")) {
                    productname = data;

                } else if (h.equalsIgnoreCase("category")) {
                    categoryid = data;
                } else if (h.equalsIgnoreCase("price")) {
                    price = data;
                } else if (h.equalsIgnoreCase("description")) {
                    description = data;
                } else if (h.equalsIgnoreCase("status")) {
                    System.out.println("status " + status);
                    status = data;
                }
            } else {
                //file data
                String filename = f.getName();
                if (filename != null && filename.length() > 0) {
                    File g = new File(filename);

                    filename = g.getName();

                    //creating unique file name
                    long w = System.currentTimeMillis();
                    filename = w + filename;
                    System.out.println("path " + path + " file " + filename);
                    //upload file
                    File t = new File(path, filename);
                    f.write(t);
                    if (f.getFieldName().equals("image")) {
                        System.out.println("images " + image);
                        image = filename;
                    }
                }

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

}