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:org.jxstar.control.action.ActionHelper.java

/**
 * ?//ww  w.ja v  a2s. co  m
 * @param request
 * @return
 */
private static Map<String, Object> parseMultiRequest(HttpServletRequest request) throws ActionException {
    //?
    DefaultFileItemFactory factory = new DefaultFileItemFactory();
    //?
    DiskFileUpload upload = new DiskFileUpload(factory);
    //????
    upload.setHeaderEncoding("utf-8");
    //?10M
    String maxSize = SystemVar.getValue("upload.file.maxsize", "10");
    upload.setSizeMax(1000 * 1000 * Integer.parseInt(maxSize));
    //?
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        _log.showError(e);
        throw new ActionException(JsMessage.getValue("fileaction.overmaxsize"), maxSize);
    }
    _log.showDebug("request item size=" + items.size());

    //
    Map<String, Object> requestMap = FactoryUtil.newMap();
    // ?
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();
        if (item.isFormField()) {
            String key = item.getFieldName();
            //?????
            String value = "";
            try {
                value = item.getString("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (key == null || key.length() == 0)
                continue;
            requestMap.put(key, value);
        } else {
            String key = item.getFieldName();
            requestMap.put(key, item);
            //??
            String fileName = item.getName();
            String contentType = item.getContentType();
            long fileSize = item.getSize();
            _log.showDebug(
                    "request filename=" + fileName + ";fileSize=" + fileSize + ";contentType=" + contentType);
        }
    }

    return requestMap;
}

From source file:org.liquidsite.core.web.MultiPartRequest.java

/**
 * Parses the incoming multi-part HTTP request.
 *
 * @param request        the HTTP request
 *
 * @throws FileUploadException if the request couldn't be parsed
 *             correctly/*from ww w .j a va  2  s . c  o m*/
 */
private void parse(HttpServletRequest request) throws FileUploadException {

    DiskFileUpload parser = new DiskFileUpload();
    List list;
    FileItem item;
    String value;

    // Create multi-part parser
    parser.setRepositoryPath(uploadDir);
    parser.setSizeMax(uploadSize);
    parser.setSizeThreshold(4096);

    // Parse request
    list = parser.parseRequest(request);
    for (int i = 0; i < list.size(); i++) {
        item = (FileItem) list.get(i);
        if (item.isFormField()) {
            try {
                value = item.getString("UTF-8");
            } catch (UnsupportedEncodingException ignore) {
                value = item.getString();
            }
            parameters.put(item.getFieldName(), value);
        } else {
            files.put(item.getFieldName(), new MultiPartFile(item));
        }
    }
}

From source file:org.mitre.mrald.util.FileUtils.java

/**
 *  Stores the image to disk. Note this will handle only one file at a time. If
 *  you want to upload more than one image, you'll have to rework this. The
 *  first non-form item encountered (a file field) is the one taken.
 *
 *@param  req                      Request that contains the upload
 *@param  user                     Description of the Parameter
 *@return                          Description of the Return Value
 *@exception  JspException         Description of the Exception
 *@exception  FileUploadException  Description of the Exception
 *@exception  IOException          Description of the Exception
 *@exception  Exception            Description of the Exception
 *@since/*from w ww  .j  av a  2  s.  c  o m*/
 */
@Deprecated
public void uploadFile(HttpServletRequest req, User user)
        throws MraldException, FileUploadException, IOException, Exception {
    if (!FileUpload.isMultipartContent(req)) {
        throw new MraldException("The supplied request did not come from a multipart request - "
                + "there can't be any file buried in here.");
    }
    /*
     *  parse the request
     */
    DiskFileUpload upload = new DiskFileUpload();
    List items = upload.parseRequest(req);
    Iterator iter = items.iterator();

    String fileName = "";

    while (iter.hasNext()) {

        FileItem fileSetItem = (FileItem) iter.next();
        String itemName = fileSetItem.getFieldName();

        if (itemName.startsWith("fileName")) {
            fileName = fileSetItem.get().toString();

        }
    }

    items.iterator();
    while (iter.hasNext()) {
        FileItem fileSetItem = (FileItem) iter.next();
        String itemName = fileSetItem.getFieldName();

        if (itemName.startsWith("settings")) {

            String dirFileName = Config.getProperty("BasePath");

            File fileFinalLocation = new File(dirFileName + "/" + fileName);
            fileSetItem.write(fileFinalLocation);
        }
    }
}

From source file:org.openhealthdata.validator.ValidatorServlet.java

/**
 * Accept a POST request with a file upload to be validated
 * Response is an XML file with an internal XSL reference
 *//*from  ww  w . ja v a  2  s. c  om*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/xml");
    PrintWriter out = response.getWriter();
    setApplicationBase(request);

    //Check that we have a file upload request
    boolean isMultipart = FileUpload.isMultipartContent(request);
    if (isMultipart) {
        // Create a new file upload handler
        DiskFileUpload upload = new DiskFileUpload();
        // Parse the request
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            logger.log(Level.SEVERE, "Exception processing upload file request", e);
            e.printStackTrace();
        }

        // Process the uploaded items
        Iterator iter = items.iterator();

        FileItem item = (FileItem) iter.next();
        StringBuffer sb = new StringBuffer();
        if (!item.isFormField()) {
            String testFileName = item.getName();
            testFileName = testFileName.replace('\\', '/');

            String[] path = testFileName.split("/");
            testFileName = path[path.length - 1];

            String[] fName = item.getName().split("\\|/");
            String fileName = "tmpValidationFile.tmp";
            if (fName.length > 0) {
                fileName = fName[fName.length - 1];
            }
            File uploadedFile = new File(fileName);
            try {
                item.write(uploadedFile);
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Exception processing uploaded file item", e);
                //e.printStackTrace();
            }
            //Add XSL Reference to result XML
            // To convert to a RESTful interface, this XSL reference could be removed
            String xslRef = "<?xml-stylesheet type=\"text/xsl\" href=\"" + applicationBase
                    + "/XSLT/validationTest.xsl\"?>";
            String xmlRef = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
            String replaceStr = "<\\?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"yes\\\"\\?>";
            String valRes = validator.validateToString(uploadedFile);
            String result = valRes.replaceFirst(replaceStr, xmlRef + xslRef);
            //Add to response stream
            sb.append(result);
            //TODO Convert to save XML files
            uploadedFile.delete();
        }
        out.print(sb.toString());
    } //END if (isMultipart)    
    out.close();
}

From source file:org.sakaiproject.connector.fck.FCKConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It stores the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*from  w ww.j  a  va2s  .  c o m*/
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    initialize();
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = null;

    String command = request.getParameter("Command");

    String currentFolder = request.getParameter("CurrentFolder");
    String collectionBase = request.getPathInfo();

    pushPrivateAdvisor(currentFolder, collectionBase);

    String fileName = "";
    String errorMessage = "";

    String status = "0";
    ContentResource attachment = null;

    if (!"FileUpload".equals(command) && !"QuickUpload".equals(command)
            && !("QuickUploadEquation").equals(command) && !("QuickUploadAttachment").equals(command)) {
        status = "203";
    } else {
        DiskFileUpload upload = new DiskFileUpload();
        String mime = "";
        InputStream requestStream = null;
        byte[] bytes = null;
        try {
            //Special case for uploading fmath equations
            if (("QuickUploadEquation").equals(command)) {
                String image = request.getParameter("image");
                String type = request.getParameter("type");
                // size protection 
                if (image == null || image.length() > 1000000)
                    return;
                bytes = Base64.decodeBase64(image);
                fileName = "fmath-equation-" + request.getParameter("name");
                if ("PNG".equals(type)) {
                    mime = "image/png";
                    if (fileName.indexOf(".") == -1) {
                        fileName += ".png";
                    }
                } else {
                    mime = "image/jpeg";
                    if (fileName.indexOf(".") == -1) {
                        fileName += ".jpg";
                    }
                }
            } else {
                //If this is a multipart request
                if (ServletFileUpload.isMultipartContent(request)) {
                    List items = upload.parseRequest(request);

                    Map fields = new HashMap();

                    Iterator iter = items.iterator();
                    while (iter.hasNext()) {
                        FileItem item = (FileItem) iter.next();
                        if (item.isFormField()) {
                            fields.put(item.getFieldName(), item.getString());
                        } else {
                            fields.put(item.getFieldName(), item);
                        }
                    }
                    FileItem uplFile = (FileItem) fields.get("NewFile");

                    String filePath = uplFile.getName();
                    filePath = filePath.replace('\\', '/');
                    String[] pathParts = filePath.split("/");
                    fileName = pathParts[pathParts.length - 1];
                    mime = uplFile.getContentType();
                    requestStream = uplFile.getInputStream();
                } else {
                    requestStream = request.getInputStream();
                    mime = request.getHeader("Content-Type");
                }
            }

            //If there's no filename, make a guid name with the mime extension?
            if ("".equals(fileName)) {
                fileName = UUID.randomUUID().toString();
            }
            String nameWithoutExt = fileName;
            String ext = "";

            if (fileName.lastIndexOf(".") > 0) {
                nameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
                ext = fileName.substring(fileName.lastIndexOf("."));
            }

            int counter = 1;
            boolean done = false;

            while (!done) {
                try {
                    ResourcePropertiesEdit resourceProperties = contentHostingService.newResourceProperties();
                    resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fileName);

                    if ("QuickUploadEquation".equals(command) || "QuickUploadAttachment".equals(command)) {
                        attachment = bypassAddAttachment(request, fileName, mime, bytes, requestStream,
                                resourceProperties);
                    } else {
                        String altRoot = getAltReferenceRoot(currentFolder);
                        if (altRoot != null)
                            resourceProperties.addProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE,
                                    altRoot);

                        int noti = NotificationService.NOTI_NONE;
                        if (bytes != null) {
                            contentHostingService.addResource(currentFolder + fileName, mime, bytes,
                                    resourceProperties, noti);
                        } else if (requestStream != null) {
                            contentHostingService.addResource(currentFolder + fileName, mime, requestStream,
                                    resourceProperties, noti);
                        } else {
                            //Nothing to do

                        }
                    }

                    done = true;
                } catch (IdUsedException iue) {
                    //the name is already used, so we do a slight rename to prevent the colision
                    fileName = nameWithoutExt + "(" + counter + ")" + ext;
                    status = "201";
                    counter++;
                }

                catch (Exception ex) {
                    //this user can't write where they are trying to write.
                    done = true;
                    ex.printStackTrace();
                    status = "203";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            status = "203";
        }
    }

    try {
        out = response.getWriter();
        if ("QuickUploadEquation".equals(command) || "QuickUploadAttachment".equals(command)) {
            out.println(attachment != null ? attachment.getUrl() : "");
        } else {
            out.println("<script type=\"text/javascript\">");
            out.println("(function(){ var d = document.domain ; while ( true ) {");
            out.println("try { var test = parent.document.domain ; break ; } catch( e ) {}");
            out.println("d = d.replace( /.*?(?:\\.|$)/, '' ) ; if ( d.length == 0 ) break ;");
            out.println("try { document.domain = d ; } catch (e) { break ; }}})() ;");

            out.println("window.parent.OnUploadCompleted(" + status + ",'"
                    + (attachment != null ? attachment.getUrl() : "") + "','"
                    + FormattedText.escapeJsQuoted(fileName) + "','" + errorMessage + "');");

            out.println("</script>");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }

    popPrivateAdvisor(currentFolder, collectionBase);
}

From source file:org.sakaiproject.tool.messageforums.FileUploadFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
        return;/*from w w  w.  ja  v a2  s.  c om*/
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest);
    if (!isMultipartContent) {
        chain.doFilter(request, response);
        return;
    }

    DiskFileUpload upload = new DiskFileUpload();
    if (repositoryPath != null) {
        upload.setRepositoryPath(repositoryPath);
    }

    try {
        List list = upload.parseRequest(httpRequest);
        final Map map = new HashMap();
        for (int i = 0; i < list.size(); i++) {
            FileItem item = (FileItem) list.get(i);
            String str = item.getString();
            if (item.isFormField()) {
                map.put(item.getFieldName(), new String[] { str });
            } else {
                httpRequest.setAttribute(item.getFieldName(), item);
            }
        }

        chain.doFilter(new HttpServletRequestWrapper(httpRequest) {
            public Map getParameterMap() {
                return map;
            }

            public String[] getParameterValues(String name) {
                Map map = getParameterMap();
                return (String[]) map.get(name);
            }

            public String getParameter(String name) {
                String[] params = getParameterValues(name);
                if (params == null) {
                    return null;
                }
                return params[0];
            }

            public Enumeration getParameterNames() {
                Map map = getParameterMap();
                return Collections.enumeration(map.keySet());
            }
        }, response);
    } catch (FileUploadException ex) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw servletEx;
    }
}

From source file:org.sakaiproject.tool.syllabus.FileUploadFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
        return;//from   w w  w. j a  v  a2  s . com
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest);
    if (!isMultipartContent) {
        chain.doFilter(request, response);
        return;
    }

    DiskFileUpload upload = new DiskFileUpload();
    if (repositoryPath != null)
        upload.setRepositoryPath(repositoryPath);

    try {
        List list = upload.parseRequest(httpRequest);
        final Map map = new HashMap();
        for (int i = 0; i < list.size(); i++) {
            FileItem item = (FileItem) list.get(i);
            String str = item.getString();
            if (item.isFormField())
                map.put(item.getFieldName(), new String[] { str });
            else
                httpRequest.setAttribute(item.getFieldName(), item);
        }

        chain.doFilter(new HttpServletRequestWrapper(httpRequest) {
            public Map getParameterMap() {
                return map;
            }

            public String[] getParameterValues(String name) {
                Map map = getParameterMap();
                return (String[]) map.get(name);
            }

            public String getParameter(String name) {
                String[] params = getParameterValues(name);
                if (params == null)
                    return null;
                return params[0];
            }

            public Enumeration getParameterNames() {
                Map map = getParameterMap();
                return Collections.enumeration(map.keySet());
            }
        }, response);
    } catch (FileUploadException ex) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw servletEx;
    }
}

From source file:org.talend.mdm.webapp.browserecords.server.servlet.UploadData.java

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

    request.setCharacterEncoding("UTF-8"); //$NON-NLS-1$
    response.setCharacterEncoding("UTF-8"); //$NON-NLS-1$
    if (!FileUploadBase.isMultipartContent(request)) {
        throw new ServletException(MESSAGES.getMessage("error_upload")); //$NON-NLS-1$
    }// w  w  w .  j a  va2  s  . c om
    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();
    // Set upload parameters
    upload.setSizeThreshold(0);
    upload.setSizeMax(-1);

    PrintWriter writer = response.getWriter();
    try {
        String concept = null;
        String seperator = null;
        String textDelimiter = "\""; //$NON-NLS-1$
        String language = "en"; //$NON-NLS-1$
        Locale locale = null;
        String encoding = "utf-8";//$NON-NLS-1$
        Map<String, Boolean> headerVisibleMap = new LinkedHashMap<String, Boolean>();
        String headerString = null;
        String mandatoryField = null;
        List<String> inheritanceNodePathList = null;
        boolean headersOnFirstLine = false;
        boolean isPartialUpdate = false;
        String multipleValueSeparator = null;
        String fileType = null;
        File file = null;
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            // FIXME: should handle more than files in parts e.g. text passed as parameter
            FileItem item = iter.next();
            if (item.isFormField()) {
                // we are not expecting any field just (one) file(s)
                String name = item.getFieldName();
                LOG.debug("doPost() Field: '" + name + "' - value:'" + item.getString() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
                if (name.equals("concept")) { //$NON-NLS-1$
                    concept = item.getString();
                } else if (name.equals("sep")) { //$NON-NLS-1$
                    seperator = item.getString();
                } else if (name.equals("delimiter")) { //$NON-NLS-1$
                    textDelimiter = item.getString();
                } else if (name.equals("language")) { //$NON-NLS-1$
                    locale = new Locale(item.getString());
                } else if (name.equals("encodings")) { //$NON-NLS-1$
                    encoding = item.getString();
                } else if (name.equals("header")) { //$NON-NLS-1$
                    headerString = item.getString();
                    List<String> headerItemList = org.talend.mdm.webapp.base.shared.util.CommonUtil
                            .convertStrigToList(headerString, Constants.FILE_EXPORT_IMPORT_SEPARATOR);
                    if (headerItemList != null) {
                        for (String headerItem : headerItemList) {
                            String[] headerItemArray = headerItem.split(Constants.HEADER_VISIBILITY_SEPARATOR);
                            headerVisibleMap.put(headerItemArray[0], Boolean.valueOf(headerItemArray[1]));
                        }
                    }
                } else if (name.equals("mandatoryField")) { //$NON-NLS-1$
                    mandatoryField = item.getString();
                } else if (name.equals("inheritanceNodePath")) { //$NON-NLS-1$
                    inheritanceNodePathList = org.talend.mdm.webapp.base.shared.util.CommonUtil
                            .convertStrigToList(item.getString(), Constants.FILE_EXPORT_IMPORT_SEPARATOR);
                } else if (name.equals("headersOnFirstLine")) { //$NON-NLS-1$
                    headersOnFirstLine = "on".equals(item.getString()); //$NON-NLS-1$
                } else if (name.equals("multipleValueSeparator")) { //$NON-NLS-1$
                    multipleValueSeparator = item.getString();
                } else if (name.equals("isPartialUpdate")) { //$NON-NLS-1$
                    isPartialUpdate = "on".equals(item.getString()); //$NON-NLS-1$
                }
            } else {
                fileType = FileUtil.getFileType(item.getName());
                file = File.createTempFile("upload", "tmp");//$NON-NLS-1$ //$NON-NLS-2$
                LOG.debug("doPost() data uploaded in " + file.getAbsolutePath()); //$NON-NLS-1$
                file.deleteOnExit();
                item.write(file);
            } // if field
        } // while item
        if (!UploadUtil.isViewableXpathValid(headerVisibleMap.keySet(), concept)) {
            throw new UploadException(MESSAGES.getMessage(locale, "error_invaild_field", concept)); //$NON-NLS-1$
        }
        Set<String> mandatorySet = UploadUtil.chechMandatoryField(
                org.talend.mdm.webapp.base.shared.util.CommonUtil.unescape(mandatoryField),
                headerVisibleMap.keySet());
        if (mandatorySet.size() > 0) {
            throw new UploadException(MESSAGES.getMessage(locale, "error_missing_mandatory_field")); //$NON-NLS-1$
        }
        UploadService service = generateUploadService(concept, fileType, isPartialUpdate, headersOnFirstLine,
                headerVisibleMap, inheritanceNodePathList, multipleValueSeparator, seperator, encoding,
                textDelimiter.charAt(0), language);

        List<WSPutItemWithReport> wsPutItemWithReportList = service.readUploadFile(file);

        putDocument(new WSPutItemWithReportArray(
                wsPutItemWithReportList.toArray(new WSPutItemWithReport[wsPutItemWithReportList.size()])),
                concept);
        writer.print(Constants.IMPORT_SUCCESS);
    } catch (Exception exception) {
        LOG.error(exception.getMessage(), exception);
        writer.print(extractErrorMessage(exception.getMessage()));
    } finally {
        writer.close();
    }
}

From source file:org.yehongyu.fckeditor.connector.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*from   w ww  .java  2s  . c o m*/
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String retVal = "0";
    String newName = "";

    UserSession us = CommonBean.getUserSession(request);
    if (us == null) {
        retVal = "405"; //
    } else {
        String myDir = baseDir + us.getUserName() + "/";
        String realBaseDir = getServletContext().getRealPath(myDir);
        File baseFile = new File(realBaseDir);
        if (!baseFile.exists()) {
            baseFile.mkdir();
        }
        //end add by yehy

        String currentPath = myDir + typeStr + currentFolderStr;
        String currentDirPath = getServletContext().getRealPath(currentPath);
        if (debug)
            System.out.println(currentDirPath);

        if (!commandStr.equals("FileUpload"))
            retVal = "203";
        else {
            DiskFileUpload upload = new DiskFileUpload();
            try {
                List items = upload.parseRequest(request);

                Map fields = new HashMap();

                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField())
                        fields.put(item.getFieldName(), item.getString());
                    else
                        fields.put(item.getFieldName(), item);
                }
                FileItem uplFile = (FileItem) fields.get("NewFile");
                String fileNameLong = uplFile.getName();
                fileNameLong = fileNameLong.replace('\\', '/');
                String[] pathParts = fileNameLong.split("/");
                String fileName = pathParts[pathParts.length - 1];

                String nameWithoutExt = getNameWithoutExtension(fileName);
                String ext = getExtension(fileName);
                File pathToSave = new File(currentDirPath, fileName);
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                    retVal = "201";
                    pathToSave = new File(currentDirPath, newName);
                    counter++;
                }
                uplFile.write(pathToSave);
            } catch (Exception ex) {
                retVal = "203";
            }

        }
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:org.yehongyu.fckeditor.uploader.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*from ww w  .  j  a va2 s  . c om*/
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    //add by yehy for sessionuser upload
    UserSession us = CommonBean.getUserSession(request);
    if (us == null) {
        errorMessage = "";
        retVal = "405";
    } else {
        String myDir = baseDir + us.getUserName() + "/";
        String realBaseDir = getServletContext().getRealPath(myDir);
        File baseFile = new File(realBaseDir);
        if (!baseFile.exists()) {
            baseFile.mkdir();
        }
        //end add by yehy

        String typeStr = request.getParameter("Type");

        String currentPath = myDir + typeStr;
        String currentDirPath = getServletContext().getRealPath(currentPath);
        if (!new File(currentDirPath + "/").exists()) {
            new File(currentDirPath + "/").mkdir();
        }
        currentPath = request.getContextPath() + currentPath;

        if (debug)
            System.out.println(currentDirPath);

        if (enabled) {
            DiskFileUpload upload = new DiskFileUpload();
            try {
                List items = upload.parseRequest(request);

                Map fields = new HashMap();

                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField())
                        fields.put(item.getFieldName(), item.getString());
                    else
                        fields.put(item.getFieldName(), item);
                }
                FileItem uplFile = (FileItem) fields.get("NewFile");
                String fileNameLong = uplFile.getName();
                fileNameLong = fileNameLong.replace('\\', '/');
                String[] pathParts = fileNameLong.split("/");
                String fileName = pathParts[pathParts.length - 1];

                String nameWithoutExt = getNameWithoutExtension(fileName);
                String ext = getExtension(fileName);
                File pathToSave = new File(currentDirPath, fileName);
                fileUrl = currentPath + "/" + fileName;
                if (extIsAllowed(typeStr, ext)) {
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                        fileUrl = currentPath + "/" + newName;
                        retVal = "201";
                        pathToSave = new File(currentDirPath, newName);
                        counter++;
                    }
                    uplFile.write(pathToSave);
                } else {
                    retVal = "202";
                    errorMessage = "";
                    if (debug)
                        System.out.println("Invalid file type: " + ext);
                }
            } catch (Exception ex) {
                if (debug)
                    ex.printStackTrace();
                retVal = "203";
            }
        } else {
            retVal = "1";
            errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
        }
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}