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

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

Introduction

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

Prototype

public DiskFileUpload() 

Source Link

Document

Constructs an instance of this class which uses the default factory to create FileItem instances.

Usage

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 www.  j  a  va2s  .com
 */
@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
 *///w w w .j  av a 2 s  .c  o m
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 w w .ja  v  a  2  s.  c  om*/
 *
 */
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;//  www  .j a  v  a  2  s.c  o  m
    }

    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 a  2  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.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$
    }/*from   www.  j  a va  2 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 w w.j  av  a  2s .  com
 *
 */
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.//www  . j a v  a 2 s. 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 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 ---");

}

From source file:oscar.DocumentMgtUploadServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    formatter = new SimpleDateFormat("yyyyMMddHmmss");
    today = new java.util.Date();
    output = formatter.format(today);//from  w  ww  .  j  av a  2s.  c o  m

    String foldername = "", fileheader = "", forwardTo = "";

    // Get properties from oscar_mcmaster.properties
    Properties ap = OscarProperties.getInstance();

    forwardTo = ap.getProperty("DOC_FORWARD");
    foldername = ap.getProperty("DOCUMENT_DIR");

    if (forwardTo == null || forwardTo.length() < 1)
        return;

    //       Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();

    try {
        //       Parse the request
        List items = upload.parseRequest(request);
        //          Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

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

            } else {
                String pathName = item.getName();
                String[] fullFile = pathName.split("[/|\\\\]");
                File savedFile = new File(foldername, output + fullFile[fullFile.length - 1]);

                fileheader = output + fullFile[fullFile.length - 1];

                item.write(savedFile);
            }
        }
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        MiscUtils.getLogger().error("Error", e);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        MiscUtils.getLogger().error("Error", e);
    }

    /*
        ServletInputStream sis = request.getInputStream();
        BufferedOutputStream dest = null;
        FileOutputStream fos = null;
        boolean bwri = false;
        boolean bfbo = true;
        boolean benddata = false;
        boolean bf = false;
        byte boundary[] = temp.getBytes();
            
        while (bf?true:((count = sis.readLine(data, 0, BUFFER)) != -1)) {
           bf = false;
           benddata = false;
                   
           if(count==2 && data[0]==13 && data[1]==10) {
              enddata[0] = 13;
              enddata[1] = 10;
              for(int i=0;i<BUFFER;i++) data[i]=0;
     count = sis.readLine(data, 0, BUFFER);
            if(count==2 && data[0]==13 && data[1]==10) {
               dest.write(enddata, 0, 2);
          bf = true;
          continue;
            } else {
          benddata = true;
            }
         }
              String s = new String(data,2,temp.length());
              if(temp.equals(s)) {
    if(benddata) break;
     if((c =sis.readLine(data1, 0, BUFFER)) != -1) {
        filename = new String(data1);
    if(filename.length()>2 && filename.indexOf("filename")!=-1) {
               
             filename = filename.substring(filename.lastIndexOf("filename=\"") + "filename\"".length() +1,
            filename.lastIndexOf('"'));
               
             filename = filename.substring(filename.lastIndexOf('\\')+1, filename.length());
             fileheader = output +  filename;
           fos = new FileOutputStream(foldername+ output + filename);
           dest = new BufferedOutputStream(fos, BUFFER);
        }
     c =sis.readLine(data2, 0, BUFFER);
               if((c =sis.readLine(data2, 0, BUFFER)) != -1) {
        bwri = bfbo?true:false;
        }
     }
     bfbo = bfbo?false:true;
     for(int i=0;i<BUFFER;i++) data[i]=0;
        continue;
              } //end period
            
            if(benddata) {
               benddata = false;
     dest.write(enddata, 0, 2);
               for(int i=0;i<2;i++) enddata[i]=0;
            }
              if(bwri) {
       dest.write(data, 0, count);
     for(int i=0;i<BUFFER;i++) data[i]=0;
              }
        } //end while
        //dest.flush();
        fos.close();
        dest.close();
        sis.close();
    */
    DocumentBean documentBean = new DocumentBean();

    request.setAttribute("documentBean", documentBean);

    documentBean.setFilename(fileheader);

    //  documentBean.setFileDesc(filedesc);

    //  documentBean.setFoldername(foldername);

    //  documentBean.setFunction(function);

    //  documentBean.setFunctionID(function_id);

    //  documentBean.setCreateDate(fileheader);

    //  documentBean.setDocCreator(creator);

    // Call the output page.

    RequestDispatcher dispatch = getServletContext().getRequestDispatcher(forwardTo);
    dispatch.forward(request, response);
}

From source file:oscar.DocumentUploadServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String foldername = "", fileheader = "", forwardTo = "";
    forwardTo = OscarProperties.getInstance().getProperty("RA_FORWORD");
    foldername = OscarProperties.getInstance().getProperty("DOCUMENT_DIR");

    String inboxFolder = OscarProperties.getInstance().getProperty("ONEDT_INBOX");
    String archiveFolder = OscarProperties.getInstance().getProperty("ONEDT_ARCHIVE");

    if (forwardTo == null || forwardTo.length() < 1)
        return;/*from w  ww  .  j av a2s.com*/

    String providedFilename = request.getParameter("filename");
    if (providedFilename != null) {

        File documentDirectory = new File(foldername);
        File providedFile = new File(inboxFolder, providedFilename);
        if (!providedFile.exists()) {
            providedFile = new File(archiveFolder, providedFilename);
        }

        FileUtils.copyFileToDirectory(providedFile, documentDirectory);

        fileheader = providedFilename;
    } else {

        DiskFileUpload upload = new DiskFileUpload();

        try {
            // Parse the request
            @SuppressWarnings("unchecked")
            List<FileItem> /* FileItem */ items = upload.parseRequest(request);
            // Process the uploaded items
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();

                if (item.isFormField()) { //
                } else {
                    String pathName = item.getName();
                    String[] fullFile = pathName.split("[/|\\\\]");
                    File savedFile = new File(foldername, fullFile[fullFile.length - 1]);
                    fileheader = fullFile[fullFile.length - 1];
                    item.write(savedFile);
                    if (OscarProperties.getInstance().isPropertyActive("moh_file_management_enabled")) {
                        FileUtils.copyFileToDirectory(savedFile, new File(inboxFolder));
                    }
                }
            }
        } catch (FileUploadException e) {
            MiscUtils.getLogger().error("Error", e);
        } catch (Exception e) {
            MiscUtils.getLogger().error("Error", e);
        }
    }

    DocumentBean documentBean = new DocumentBean();
    request.setAttribute("documentBean", documentBean);
    documentBean.setFilename(fileheader);
    RequestDispatcher dispatch = getServletContext().getRequestDispatcher(forwardTo);
    dispatch.forward(request, response);
}