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:com.javaweb.controller.SuaTinTucServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from  w w w.j  a v a 2s.c  om*/
 * @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, ParseException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    //response.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 0, idtt = 0;

    TintucService tintucservice = new TintucService();

    //File upload
    String folderupload = getServletContext().getInitParameter("file-upload");
    String rootPath = getServletContext().getRealPath("/");
    filePath = rootPath + folderupload;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("C:\\Windows\\Temp\\"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    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()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters

                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();

                //change file name
                fileName = FileService.ChangeFileName(fileName);

                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + "/" + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                //                    out.println("Uploaded Filename: " + fileName + "<br>");
            }

            if (fi.isFormField()) {
                if (fi.getFieldName().equalsIgnoreCase("TieuDe")) {
                    TieuDe = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) {
                    NoiDung = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) {
                    ngaydang = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) {
                    GhiChu = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) {
                    idloaitin = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) {
                    idTK = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtt")) {
                    idtt = Integer.parseInt(fi.getString("UTF-8"));
                }
            }
        }

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

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);

    Tintuc tt = tintucservice.GetTintucID(idtt);

    tt.setIdTaiKhoan(idTK);
    tt.setTieuDe(TieuDe);
    tt.setNoiDung(NoiDung);
    tt.setNgayDang(NgayDang);
    tt.setGhiChu(GhiChu);
    if (!fileName.equals("")) {
        if (tt.getImgLink() != null) {
            if (!tt.getImgLink().equals(fileName)) {
                tt.setImgLink(fileName);
            }
        } else {
            tt.setImgLink(fileName);
        }
    }

    boolean rs = tintucservice.InsertTintuc(tt);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    } else {
        session.setAttribute("kiemtra", "0");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    }

    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet SuaTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet SuaTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:bijian.util.upload.MyMultiPartRequest.java

private List<FileItem> parseRequest(HttpServletRequest servletRequest, String saveDir)
        throws FileUploadException {
    DiskFileItemFactory fac = createDiskFileItemFactory(saveDir);
    ServletFileUpload upload = new ServletFileUpload(fac);
    upload.setSizeMax(maxSize);//from   ww w .  j  av a2 s  .  c  o m
    FileUploadListener myFileUploadListener = new FileUploadListener(servletRequest);
    upload.setProgressListener(myFileUploadListener);
    return upload.parseRequest(createRequestContext(servletRequest));
}

From source file:com.gwtcx.server.servlet.FileUploadServlet.java

@SuppressWarnings("rawtypes")
private void processFiles(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

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

    // set the size threshold, above which content will be stored on disk
    factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB

    // set the temporary directory (this is where files that exceed the threshold will be stored)
    factory.setRepository(tmpDir);/*ww  w. j  a  v  a2 s.  c o m*/

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

    try {
        String recordType = "Account";

        // parse the request
        List items = upload.parseRequest(request);

        // process the uploaded items
        Iterator itr = items.iterator();

        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // process a regular form field
            if (item.isFormField()) {
                Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getString());

                if (item.getFieldName().equals("recordType")) {
                    recordType = item.getString();
                }
            } else { // process a file upload

                Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getName()
                        + ", Content Type: " + item.getContentType() + ", In Memory: " + item.isInMemory()
                        + ", File Size: " + item.getSize());

                // write the uploaded file to the application's file staging area
                File file = new File(destinationDir, item.getName());
                item.write(file);

                // import the CSV file
                importCsvFile(recordType, file.getPath());

                // file.delete();  // TO DO
            }
        }
    } catch (FileUploadException e) {
        Log.error("Error encountered while parsing the request", e);
    } catch (Exception e) {
        Log.error("Error encountered while uploading file", e);
    }
}

From source file:com.naval.persistencia.hibernate.SubirArchivo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  ww  .ja v a2 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 {
    HttpSession sesion = request.getSession();
    response.setContentType("text/html;charset=UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();

    response.setContentType("text/plain");
    String ultimoMatenimiento = (String) sesion.getAttribute("ultimaSolicitud");

    List<FileItem> items;
    try {
        items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {

                FileItem actual = null;
                actual = item;
                String fileName = actual.getName();

                String str = request.getSession().getServletContext().getRealPath("/adjuntos/");
                fileName = ultimoMatenimiento + "-" + fileName;
                // nos quedamos solo con el nombre y descartamos el path
                File fichero = new File(str + "\\" + fileName);

                try {
                    actual.write(fichero);
                    String aux = "{" + "\"name\":\"" + fichero.getName() + "\",\"size\":\"" + 2000
                            + "\",\"url\":\"/adjuntos/" + fichero.getName()
                            + "\",\"thumbnailUrl\":\"/thumbnails/" + fichero.getName()
                            + "\",\"deleteUrl\":\"/Subir?file=" + fichero.getName()
                            + "\",\"deleteType\":\"DELETE" + "\",\"type\":\"" + fichero.getName() + "\"}";

                    writer.write("{\"files\":[" + aux + "]}");
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception ex) {
    }
}

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

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

    // Get File name and extension
    EntityUtils eut = getEntityUtils(req);
    String name = req.getParameter(FNAME);
    String dname = req.getParameter(DNAME);

    HashSet<String> extl;
    try {
        extl = getExtListByDirName(eut, dname);
    } catch (WsSrvException e) {
        checkSendError(req, resp, e);
        return;
    }

    // Check if rename required
    String rename = req.getParameter("rename_to");
    if (rename != null) {
        if (rename.equals("")) {
            //-- 235
            checkSendError(req, resp, 235, "Empty parameter rename_to");
            return;
        }

        try {
            GenericUtils.renameFile(getPrjRootDir(req), name, rename, extl, dname);
        } catch (WsSrvException e) {
            checkSendError(req, resp, e);
        }
    } else {
        try {
            if (!ServletFileUpload.isMultipartContent(req)) {
                //-- 255
                checkSendError(req, resp, 255, "Request is not multipart");
                return;
            }

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

            InputStream in = null;
            List<FileItem> items;
            try {
                items = upload.parseRequest(req);
            } catch (FileUploadException e) {
                //-- 256
                checkSendError(req, resp, 256, "Error parsing request", null, e);
                return;
            }

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

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

            String res = ExFileUtils.createFile(getPrjRootDir(req), name, in, extl, dname,
                    getReqParamValues(req), getEntityUtils(req), isMinfied(req),
                    req.getParameter("overwrite") != null);
            printJson(resp, Utils.isEmpty(res) ? "{}" : res);
        } catch (WsSrvException e) {
            checkSendError(req, resp, e);
        }
    }
}

From source file:controllers.IndexController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView uploadpic(HttpServletRequest request, ModelAndView model) {

    String path = request.getRealPath("/upload_images");
    path = path.substring(0, path.indexOf("\\mavenproject1"));
    path = path + "\\mavenproject1\\mavenproject1\\src\\main\\webapp\\upload_images";
    DiskFileItemFactory dfif = new DiskFileItemFactory();
    ServletFileUpload uploader = new ServletFileUpload(dfif);

    try {//  www .  j  a  v a  2 s . co  m

        List<FileItem> fit = uploader.parseRequest(request);
        for (FileItem fileItem : fit) {
            try {
                contenttype = fileItem.getContentType();
                contenttype = contenttype.substring(6, contenttype.length());
                if (fileItem.isFormField() == false && contenttype.equals("jpeg")
                        || contenttype.equals("png")) {
                    file = new File(path + "/" + fileItem.getName());
                    fileItem.write(file);

                }
            } catch (Exception ey) {

            }

        }
        return model;
    } catch (Exception ex) {

        if (file.exists()) {

            file.delete();
        }

        model.addObject("errorcode", ex.toString());
        model.setViewName("nosuccessform");
        return model;
    }

}

From source file:gov.nist.appvet.tool.synchtest.Service.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get received HTTP parameters and file upload
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = null;//from   w  w w.  j a va 2s . c  o m
    FileItem fileItem = null;

    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // Get received items
    Iterator iter = items.iterator();
    FileItem item = null;

    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (item.isFormField()) {
            // Get HTML form parameters
            String incomingParameter = item.getFieldName();
            String incomingValue = item.getString();
            if (incomingParameter.equals("appid")) {
                appId = incomingValue;
                log.info("Received app ID: " + appId);
            }
            /** CHANGE (START): Get other tools-specific form parameters **/
            /** CHANGE (END): Get other tools-specific form parameters **/
        } else {
            // item should now hold the received file
            if (item != null) {
                fileItem = item;
                log.info("Received file: " + fileItem.getName());
            }
        }
    }

    if (appId == null) {
        // All tool services require an AppVet app ID
        log.error("Received null app ID. Returning HTTP 400");
        HttpUtil.sendHttp400(response, "No app ID specified");
        return;
    }

    if (fileItem != null) {
        // Get app file
        fileName = FileUtil.getFileName(fileItem.getName());
        if (!fileName.endsWith(".apk")) {
            log.error("Received invalid app file. Returning HTTP 400");
            HttpUtil.sendHttp400(response, "Invalid app file: " + fileItem.getName());
            return;
        }
        // Create app directory
        appDirPath = Properties.TEMP_DIR + "/" + appId;
        File appDir = new File(appDirPath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        // Create report path
        reportFilePath = Properties.TEMP_DIR + "/" + appId + "/" + reportName + "."
                + Properties.reportFormat.toLowerCase();

        appFilePath = Properties.TEMP_DIR + "/" + appId + "/" + fileName;
        log.debug("App file path: " + appFilePath);
        if (!FileUtil.saveFileUpload(fileItem, appFilePath)) {
            log.error("Could not save file. Returning HTTP 500");
            HttpUtil.sendHttp500(response, "Could not save uploaded file");
            return;
        }
        log.debug("Saved app file");
    } else {
        HttpUtil.sendHttp400(response, "No app was received.");
        return;
    }

    // Use if reading command from ToolProperties.xml. Otherwise,
    // comment-out if using custom command (called by customExecute())
    //command = getCommand();

    /*
     * CHANGE: Select either execute() to execute a native OS command or
     * customExecute() to execute your own custom code. Make sure that the
     * unused method call is commented-out.
     */
    reportBuffer = new StringBuffer();
    boolean succeeded = customExecute(reportBuffer);
    if (!succeeded) {
        log.error("Error detected: " + reportBuffer.toString());
        String errorReport = ReportUtil.getHtmlReport(response, fileName, ToolStatus.ERROR,
                reportBuffer.toString());
        // Send report to AppVet
        if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) {
            // Send back ASCII in HTTP Response
            ReportUtil.sendInHttpResponse(response, errorReport, ToolStatus.ERROR);
        }
        return;
    }

    // Analyze report and generate tool status
    log.info("Analyzing report for " + appFilePath);
    //      ToolStatus risk = ReportUtil.analyzeReport(reportBuffer
    //            .toString());
    ToolStatus risk = ToolStatus.LOW; // Just set to LOW for testing
    log.info("Result: " + risk.name());
    String reportContent = null;

    // Get report
    if (Properties.reportFormat.equals(ReportFormat.HTML.name())) {
        reportContent = ReportUtil.getHtmlReport(response, fileName, risk, reportBuffer.toString());
    }
    //      else if (Properties.reportFormat.equals(ReportFormat.TXT.name())) {
    //         reportContent = getTxtReport();
    //      } else if (Properties.reportFormat.equals(ReportFormat.PDF.name())) {
    //         reportContent = getPdfReport();
    //      } else if (Properties.reportFormat.equals(ReportFormat.JSON.name())) {
    //         reportContent = getJsonReport();
    //      }

    // If report is null or empty, stop processing
    if (reportContent == null || reportContent.isEmpty()) {
        log.error("Tool report is null or empty");
        return;
    } else {
        log.info("Report generated");
    }

    // Send report to AppVet
    if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) {
        // Send back ASCII in HTTP Response
        ReportUtil.sendPDFInHttpResponse(response, reportContent, risk);
    }

    // Clean up
    if (!Properties.keepApps) {
        if (FileUtil.deleteDirectory(new File(appDirPath))) {
            log.debug("Deleted " + appFilePath);
        } else {
            log.error("Could not delete " + appFilePath);
        }
    }
    log.info("Done processing app " + appId);
    reportBuffer = null;
    System.gc();
}

From source file:importer.handler.post.ImporterPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request//from  ww  w.j  a  v  a  2 s .  c  o m
 */
void parseImportParams(HttpServletRequest request) throws AeseException {
    try {
        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();
                    if (fieldName.equals(Params.DOCID)) {
                        if (contents.startsWith("/")) {
                            contents = contents.substring(1);
                            int pos = contents.indexOf("/");
                            if (pos != -1) {
                                database = contents.substring(0, pos);
                                contents = contents.substring(pos + 1);
                            }
                        }
                        docid = contents;
                    } else if (fieldName.startsWith(Params.SHORT_VERSION))
                        nameMap.put(fieldName.substring(Params.SHORT_VERSION.length()), item.getString());
                    else if (fieldName.equals(Params.LC_STYLE) || fieldName.equals(Params.STYLE)
                            || fieldName.equals(Params.CORFORM)) {
                        jsonKeys.put(fieldName.toLowerCase(), contents);
                        style = contents;
                    } else if (fieldName.equals(Params.DEMO)) {
                        if (contents != null && contents.equals("brillig"))
                            demo = false;
                        else
                            demo = true;
                    } else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.FILTER))
                        filterName = contents.toLowerCase();
                    else if (fieldName.equals(Params.SIMILARITY))
                        similarityTest = contents != null && contents.equals("1");
                    else if (fieldName.equals(Params.SPLITTER))
                        splitterName = contents;
                    else if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.TEXT))
                        textName = contents.toLowerCase();
                    else if (fieldName.equals(Params.DICT))
                        dict = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.HH_EXCEPTIONS))
                        hhExceptions = contents;
                    else
                        jsonKeys.put(fieldName, contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // assuming that the contents are text
                    //item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null && type.startsWith("image/")) {
                        InputStream is = item.getInputStream();
                        ByteHolder bh = new ByteHolder();
                        while (is.available() > 0) {
                            byte[] b = new byte[is.available()];
                            is.read(b);
                            bh.append(b);
                        }
                        ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData());
                        images.add(iFile);
                    } else {
                        byte[] rawData = item.get();
                        guessEncoding(rawData);
                        //System.out.println(encoding);
                        File f = new File(item.getName(), new String(rawData, encoding));
                        files.add(f);
                    }
                } catch (Exception e) {
                    throw new AeseException(e);
                }
            }
        }
        if (style == null)
            style = DEFAULT_STYLE;
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:com.tremolosecurity.proxy.ProxyRequest.java

public ProxyRequest(HttpServletRequest req, HttpSession session) throws Exception {
    super(req);//w w  w.  j  a  va  2 s.c o  m

    this.session = session;

    ServletRequestContext reqCtx = new ServletRequestContext(req);
    this.isMultiPart = "POST".equalsIgnoreCase(req.getMethod()) && reqCtx.getContentType() != null
            && reqCtx.getContentType().toLowerCase(Locale.ENGLISH).startsWith("multipart/form-data");

    this.isParamsInBody = true;
    this.isPush = false;
    this.paramList = new ArrayList<String>();

    this.reqParams = new HashMap<String, ArrayList<String>>();
    this.queryString = new ArrayList<NVP>();

    HttpServletRequest request = (HttpServletRequest) super.getRequest();

    if (request.getQueryString() != null && !request.getQueryString().isEmpty()) {
        StringTokenizer toker = new StringTokenizer(request.getQueryString(), "&");
        while (toker.hasMoreTokens()) {
            String qp = toker.nextToken();
            int index = qp.indexOf('=');
            if (index > 0) {
                String name = qp.substring(0, qp.indexOf('='));
                String val = URLDecoder.decode(qp.substring(qp.indexOf('=') + 1), "UTf-8");
                this.queryString.add(new NVP(name, val));
            }
        }
    }

    if (this.isMultiPart) {
        this.isPush = true;
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

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

        List<FileItem> items = upload.parseRequest(req);

        this.reqFiles = new HashMap<String, ArrayList<FileItem>>();

        for (FileItem item : items) {
            //this.paramList.add(item.getName());

            if (item.isFormField()) {
                ArrayList<String> vals = this.reqParams.get(item.getFieldName());
                if (vals == null) {
                    vals = new ArrayList<String>();
                    this.reqParams.put(item.getFieldName(), vals);
                }
                this.paramList.add(item.getFieldName());

                vals.add(item.getString());
            } else {
                ArrayList<FileItem> vals = this.reqFiles.get(item.getFieldName());
                if (vals == null) {
                    vals = new ArrayList<FileItem>();
                    this.reqFiles.put(item.getFieldName(), vals);
                }

                vals.add(item);
            }
        }

    } else {
        Enumeration enumer = req.getHeaderNames();

        String contentType = null;

        while (enumer.hasMoreElements()) {
            String name = (String) enumer.nextElement();
            if (name.equalsIgnoreCase("content-type") || name.equalsIgnoreCase("content-length")) {
                this.isPush = true;
                if (name.equalsIgnoreCase("content-type")) {
                    contentType = req.getHeader(name);
                }
            }

        }

        if (this.isPush) {
            if (contentType == null || !contentType.startsWith("application/x-www-form-urlencoded")) {
                this.isParamsInBody = false;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream in = req.getInputStream();
                int len;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) > 0) {

                    baos.write(buffer, 0, len);
                }

                req.setAttribute(ProxySys.MSG_BODY, baos.toByteArray());
            } else if (contentType.startsWith("application/x-www-form-urlencoded")) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream in = req.getInputStream();
                int len;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) > 0) {

                    baos.write(buffer, 0, len);
                }

                StringTokenizer toker = new StringTokenizer(new String(baos.toByteArray()), "&");
                this.orderedList = new ArrayList<NVP>();
                while (toker.hasMoreTokens()) {
                    String token = toker.nextToken();
                    int index = token.indexOf('=');

                    String name = token.substring(0, index);

                    if (name.indexOf('%') != -1) {
                        name = URLDecoder.decode(name, "UTF-8");
                    }

                    String val = "";
                    if (index < (token.length() - 1)) {
                        val = URLDecoder.decode(token.substring(token.indexOf('=') + 1), "UTF-8");
                    }

                    this.orderedList.add(new NVP(name, val));
                    this.paramList.add(name);
                    ArrayList<String> params = this.reqParams.get(name);
                    if (params == null) {
                        params = new ArrayList<String>();
                        this.reqParams.put(name, params);
                    }

                    params.add(val);
                }
            }
        }
    }

}

From source file:cc.kune.core.server.manager.file.FileUploadManagerAbstract.java

@Override
@SuppressWarnings({ "rawtypes" })
protected void doPost(final HttpServletRequest req, final HttpServletResponse response)
        throws ServletException, IOException {

    beforePostStart();/*from  w w w  . java  2s .  com*/

    final DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    factory.setRepository(new File("/tmp"));

    if (!ServletFileUpload.isMultipartContent(req)) {
        LOG.warn("Not a multipart upload");
    }

    final ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown
    upload.setSizeMax(kuneProperties.getLong(KuneProperties.UPLOAD_MAX_FILE_SIZE) * 1024 * 1024);

    try {
        final List fileItems = upload.parseRequest(req);
        String userHash = null;
        StateToken stateToken = null;
        String typeId = null;
        String fileName = null;
        FileItem file = null;
        for (final Iterator iterator = fileItems.iterator(); iterator.hasNext();) {
            final FileItem item = (FileItem) iterator.next();
            if (item.isFormField()) {
                final String name = item.getFieldName();
                final String value = item.getString();
                LOG.info("name: " + name + " value: " + value);
                if (name.equals(FileConstants.HASH)) {
                    userHash = value;
                }
                if (name.equals(FileConstants.TOKEN)) {
                    stateToken = new StateToken(value);
                }
                if (name.equals(FileConstants.TYPE_ID)) {
                    typeId = value;
                }
            } else {
                fileName = item.getName();
                LOG.info("file: " + fileName + " fieldName: " + item.getFieldName() + " size: " + item.getSize()
                        + " typeId: " + typeId);
                file = item;
            }
        }
        createUploadedFile(userHash, stateToken, fileName, file, typeId);
        onSuccess(response);
    } catch (final FileUploadException e) {
        onFileUploadException(response);
    } catch (final Exception e) {
        onOtherException(response, e);
    }
}