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:fr.paris.lutece.util.http.MultipartUtil.java

/**
 * Convert a HTTP request to a {@link MultipartHttpServletRequest}
 * @param nSizeThreshold the size threshold
 * @param nRequestSizeMax the request size max
 * @param bActivateNormalizeFileName true if the file name must be normalized, false otherwise
 * @param request the HTTP request/*  www  .  j a va2 s.c o m*/
 * @return a {@link MultipartHttpServletRequest}, null if the request does not have a multipart content
 * @throws SizeLimitExceededException exception if the file size is too big
 * @throws FileUploadException exception if an unknown error has occurred
 */
public static MultipartHttpServletRequest convert(int nSizeThreshold, long nRequestSizeMax,
        boolean bActivateNormalizeFileName, HttpServletRequest request)
        throws SizeLimitExceededException, FileUploadException {
    if (isMultipart(request)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(nSizeThreshold);

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

        // Set overall request size constraint
        upload.setSizeMax(nRequestSizeMax);

        // get encoding to be used
        String strEncoding = request.getCharacterEncoding();

        if (strEncoding == null) {
            strEncoding = EncodingService.getEncoding();
        }

        Map<String, FileItem> mapFiles = new HashMap<String, FileItem>();
        Map<String, String[]> mapParameters = new HashMap<String, String[]>();

        List<FileItem> listItems = upload.parseRequest(request);

        // Process the uploaded items
        for (FileItem item : listItems) {
            if (item.isFormField()) {
                String strValue = StringUtils.EMPTY;

                try {
                    if (item.getSize() > 0) {
                        strValue = item.getString(strEncoding);
                    }
                } catch (UnsupportedEncodingException ex) {
                    if (item.getSize() > 0) {
                        // if encoding problem, try with system encoding
                        strValue = item.getString();
                    }
                }

                // check if item of same name already in map
                String[] curParam = mapParameters.get(item.getFieldName());

                if (curParam == null) {
                    // simple form field
                    mapParameters.put(item.getFieldName(), new String[] { strValue });
                } else {
                    // array of simple form fields
                    String[] newArray = new String[curParam.length + 1];
                    System.arraycopy(curParam, 0, newArray, 0, curParam.length);
                    newArray[curParam.length] = strValue;
                    mapParameters.put(item.getFieldName(), newArray);
                }
            } else {
                // multipart file field, if the parameter filter ActivateNormalizeFileName is set to true
                //all file name will be normalize
                mapFiles.put(item.getFieldName(),
                        bActivateNormalizeFileName ? new NormalizeFileItem(item) : item);
            }
        }

        return new MultipartHttpServletRequest(request, mapFiles, mapParameters);
    }

    return null;
}

From source file:com.acciente.commons.htmlform.Parser.java

private static Map parsePOSTMultiPart(HttpServletRequest oRequest, int iStoreFileOnDiskThresholdInBytes,
        File oUploadedFileStorageDir) throws FileUploadException, IOException, ParserException {
    Map oMultipartParams = new HashMap();

    // we have multi-part content, we process it with apache-commons-fileupload

    ServletFileUpload oMultipartParser = new ServletFileUpload(
            new DiskFileItemFactory(iStoreFileOnDiskThresholdInBytes, oUploadedFileStorageDir));

    List oFileItemList = oMultipartParser.parseRequest(oRequest);

    for (Iterator oIter = oFileItemList.iterator(); oIter.hasNext();) {
        FileItem oFileItem = (FileItem) oIter.next();

        // we support the variable name to use the full syntax allowed in non-multipart forms
        // so we use parseParameterSpec() to support array and map variable syntaxes in multi-part mode
        Reader oParamNameReader = null;
        ParameterSpec oParameterSpec = null;

        try {/*from w  w w  .ja va 2  s. co  m*/
            oParamNameReader = new StringReader(oFileItem.getFieldName());

            oParameterSpec = Parser.parseParameterSpec(oParamNameReader,
                    oFileItem.isFormField() ? Symbols.TOKEN_VARTYPE_STRING : Symbols.TOKEN_VARTYPE_FILE);
        } finally {
            if (oParamNameReader != null) {
                oParamNameReader.close();
            }
        }

        if (oFileItem.isFormField()) {
            Parser.addParameter2Form(oMultipartParams, oParameterSpec, oFileItem.getString(), false);
        } else {
            Parser.addParameter2Form(oMultipartParams, oParameterSpec, oFileItem);
        }
    }

    return oMultipartParams;
}

From source file:com.easyjf.web.core.FrameworkEngine.java

/**
 * ?requestform//from  ww w .  j  av a  2s .  co m
 * 
 * @param request
 * @param formName
 * @return ??Form
 */
public static WebForm creatWebForm(HttpServletRequest request, String formName, Module module) {
    Map textElement = new HashMap();
    Map fileElement = new HashMap();
    String contentType = request.getContentType();
    String reMethod = request.getMethod();
    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))
            && (reMethod.equalsIgnoreCase("post"))) {
        //  multipart/form-data
        File file = new File(request.getSession().getServletContext().getRealPath("/temp"));
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(webConfig.getUploadSizeThreshold());
        factory.setRepository(file);
        ServletFileUpload sf = new ServletFileUpload(factory);
        sf.setSizeMax(webConfig.getMaxUploadFileSize());
        sf.setHeaderEncoding(request.getCharacterEncoding());
        List reqPars = null;
        try {
            reqPars = sf.parseRequest(request);
            for (int i = 0; i < reqPars.size(); i++) {
                FileItem it = (FileItem) reqPars.get(i);
                if (it.isFormField()) {
                    textElement.put(it.getFieldName(), it.getString(request.getCharacterEncoding()));// ??
                } else {
                    fileElement.put(it.getFieldName(), it);// ???
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
    } else if ((contentType != null) && contentType.equals("text/xml")) {
        StringBuffer buffer = new StringBuffer();
        try {
            String s = request.getReader().readLine();
            while (s != null) {
                buffer.append(s + "\n");
                s = request.getReader().readLine();
            }
        } catch (Exception e) {
            logger.error(e);
        }
        textElement.put("xml", buffer.toString());
    } else {
        textElement = request2map(request);
    }
    // logger.debug("????");
    WebForm wf = findForm(formName);
    wf.setValidate(module.isValidate());// ?validate?Form
    if (wf != null) {
        wf.setFileElement(fileElement);
        wf.setTextElement(textElement);
    }
    return wf;
}

From source file:com.zlfun.framework.excel.ExcelUtils.java

public static <T> List<T> httpInput(HttpServletRequest request, Class<T> clazz) {
    List<T> result = new ArrayList<T>();
    //??  /*w  w w  .  ja v a 2 s  .c om*/
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //??  
    String path = request.getSession().getServletContext().getRealPath("/");
    factory.setRepository(new File(path));
    // ??   
    factory.setSizeThreshold(1024 * 1024);
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        //?  
        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : list) {
            //????  
            String name = item.getFieldName();

            //? ??  ?  
            if (item.isFormField()) {
                //? ??????   
                String value = item.getString();

                request.setAttribute(name, value);
            } //? ??    
            else {
                /**
                 * ?? ??
                 */
                //???  
                String value = item.getName();
                //????  

                fill(clazz, result, value, item.getInputStream());

                //??
            }
        }

    } catch (FileUploadException ex) {
        // TODO Auto-generated catch block      excel=null;
        Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {

        Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:com.intel.cosbench.controller.handler.ConfigHandler.java

@SuppressWarnings("unchecked")
private InputStream retrieveConfigStream(HttpServletRequest request) throws Exception {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    for (FileItem item : (List<FileItem>) upload.parseRequest(request))
        if (item.getFieldName().equals("config"))
            return item.getInputStream();
    throw new BadRequestException();
}

From source file:database.FileMgr.java

public void upload(HttpServletRequest request) throws Exception {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        List items = upload.parseRequest(request);
        Iterator iterator = items.iterator();
        while (iterator.hasNext()) {
            FileItem item = (FileItem) iterator.next();

            if (!item.isFormField()) {
                String fileName = item.getName();

                if (!path.exists()) {
                    boolean status = path.mkdirs();
                }//  ww  w . j  a v a 2  s  . c o  m
                String dir = path + "/" + fileName;

                File uploadedFile = new File(dir);
                if (!(uploadedFile.exists() && !uploadedFile.isDirectory())) {

                    //System.out.println(uploadedFile.getAbsolutePath());
                    item.write(uploadedFile);
                } else {
                    throw new Exception("File exist");
                }
            }
        }

    }
}

From source file:com.UploadAction.java

public String execute() throws Exception {
    try {/*from   w  w  w .j a  va 2 s. c o m*/
        //long maxFileSize = (2 * 1024 * 1024);
        //int maxMemSize = (2 * 1024 * 1024);
        //final String path = "/tmp";
        HttpServletRequest request = ServletActionContext.getRequest();
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                if (fileItem.isFormField()) {
                    //processFormField(fileItem);
                } else {
                    flItem = fileItem;
                }
            }
        }
        HttpSession session = ServletActionContext.getRequest().getSession(false);
        String User = (String) session.getAttribute("username");
        Connection con = Connections.conn();
        PreparedStatement stat = con.prepareStatement("update user set image=? where UserName=?");
        stat.setString(2, User);
        stat.setBinaryStream(1, flItem.getInputStream(), (int) flItem.getSize());
        // stat.setBinaryStream(4, (InputStream) itemPhoto.getInputStream(), (int) itemPhoto.getSize());
        int rows = stat.executeUpdate();
        if (rows > 0) {
            return "success";
        }
    } catch (Exception e) {
    }
    return "success";
}

From source file:com.liferay.samplestruts.struts.action.UploadAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    FileItemFactory factory = new DiskFileItemFactory();

    ServletFileUpload upload = new ServletFileUpload(factory);

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

    Iterator<FileItem> itr = items.iterator();

    String itemName = StringPool.BLANK;

    while (itr.hasNext()) {
        FileItem item = itr.next();//from   ww  w .j  a v a  2  s  . c om

        if (!item.isFormField()) {
            if (_log.isInfoEnabled()) {
                _log.info("Field name " + item.getFieldName());
            }

            itemName = item.getName();

            if (_log.isInfoEnabled()) {
                _log.info("Name " + itemName);
                _log.info("Content type " + item.getContentType());
                _log.info("In memory " + item.isInMemory());
                _log.info("Size " + item.getSize());
            }
        }
    }

    request.setAttribute("file_name", itemName);

    return mapping.findForward("/sample_struts_portlet/upload_success");
}

From source file:com.certus.actions.uploadSliderImageAction.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = getServletContext().getRealPath("img/slider").replace("build/", "");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {/*from   ww w.  j  a v  a 2  s  .  c  o m*/
            List<FileItem> multiparts = upload.parseRequest(request);
            StringBuilder sb = null;
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    double randomA = Math.random() * 1000000000;
                    int randA = (int) randomA;
                    String name = new File(item.getName()).getName();
                    sb = new StringBuilder(name);
                    sb.replace(0, name.length() - 4, "slider-" + randA);
                    item.write(new File(path + File.separator + sb));
                }
            }
            String pathTo = path + File.separator + sb;
            response.getWriter().write(pathTo.substring(pathTo.lastIndexOf("img")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:net.formio.servlet.ServletMultipartRequestParser.java

@Override
protected List<FileItem> parseRequest(FileItemFactory fif, long singleFileSizeMax, long totalSizeMax,
        String defaultEncoding) throws FileUploadException {
    final ServletFileUpload upload = new ServletFileUpload(fif);
    configureUpload(upload, singleFileSizeMax, totalSizeMax, defaultEncoding);
    return upload.parseRequest(request);
}