Example usage for org.apache.commons.fileupload FileItem getString

List of usage examples for org.apache.commons.fileupload FileItem getString

Introduction

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

Prototype

String getString();

Source Link

Document

Returns the contents of the file item as a String, using the default character encoding.

Usage

From source file:it.univaq.servlet.Modifica_pub.java

protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception {
    HttpSession s = SecurityLayer.checkSession(request);
    //dichiaro mappe 
    Map pubb = new HashMap();
    Map rist = new HashMap();
    Map key = new HashMap();
    Map files = new HashMap();
    Map modifica = new HashMap();

    int id = Integer.parseInt(request.getParameter("id"));

    if (ServletFileUpload.isMultipartContent(request)) {

        //La dimensione massima di ogni singolo file su system
        int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
        //Dimensione massima della request
        int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB

        // Creo un factory per l'accesso al filesystem
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Setto la dimensione massima di ogni file, opzionale
        factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);

        // Istanzio la classe per l'upload
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Setto la dimensione massima della request
        upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

        // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
        // tutti i field sia di tipo file che gli altri
        List<FileItem> items = upload.parseRequest(request);

        /*/*w w  w  .  j a  va2  s  .c om*/
        * La classe usata non permette di riprendere i singoli campi per
        * nome quindi dovremmo scorrere la lista che ci viene ritornata con
        * il metodo parserequest
        */
        //scorro per tutti i campi inviati
        for (int i = 0; i < items.size(); i++) {
            FileItem item = items.get(i);
            // Controllo se si tratta di un campo di input normale
            if (item.isFormField()) {
                // Prendo solo il nome e il valore
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equals("titolo") || name.equals("autore") || name.equals("descrizione")) {
                    pubb.put(name, value);
                } else if (name.equals("isbn") || name.equals("editore") || name.equals("lingua")
                        || name.equals("numpagine") || name.equals("datapubbl")) {
                    rist.put(name, value);
                } else if (name.equals("key1") || name.equals("key2") || name.equals("key3")
                        || name.equals("key4")) {
                    key.put(name, value);
                } else if (name.equals("descrizionemod")) {
                    modifica.put(name, value);
                }

            } // Se si stratta invece di un file
            else {
                // Dopo aver ripreso tutti i dati disponibili name,type,size
                //String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                long sizeInBytes = item.getSize();
                //li salvo nella mappa
                files.put("name", fileName);
                files.put("type", contentType);
                files.put("size", sizeInBytes);
                //li scrivo nel db
                //Database.connect();
                Database.insertRecord("files", files);
                //Database.close();

                // Posso scriverlo direttamente su filesystem
                if (true) {
                    File uploadedFile = new File(
                            getServletContext().getInitParameter("uploads.directory") + fileName);
                    // Solo se veramente ho inviato qualcosa
                    if (item.getSize() > 0) {
                        item.write(uploadedFile);
                    }
                }
            }

        }

        pubb.put("idutente", s.getAttribute("userid"));
        modifica.put("userid", s.getAttribute("userid"));
        modifica.put("idpubb", id);

        try {
            //    if(Database.updateRecord("keyword", key, "id="+id)){

            //aggiorno ora la pubblicazione con tutti i dati
            Database.updateRecord("keyword", key, "id=" + id);
            Database.updateRecord("pubblicazione", pubb, "id=" + id);
            Database.updateRecord("ristampa", rist, "idpub=" + id);
            Database.insertRecord("storia", modifica);

            //    //vado alla pagina di corretto inserimento

            return true;
        } catch (SQLException ex) {
            Logger.getLogger(Modifica_pub.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else
        return false;
    return false;
}

From source file:com.runwaysdk.controller.ServletDispatcher.java

/**
 * @param req/* w  ww .  java 2s  .c om*/
 * @param annotation
 * @return
 * @throws FileUploadException
 */
@SuppressWarnings("unchecked")
private Map<String, Parameter> getParameters(HttpServletRequest req, ActionParameters annotation) {
    String mojaxObject = req.getParameter(MOJAX_OBJECT);

    if (mojaxObject != null) {
        try {
            return this.getParameterMap(new MojaxObjectParser(annotation, mojaxObject).getMap());
        } catch (JSONException e) {
            throw new ClientException(e);
        }
    } else {
        if (ServletFileUpload.isMultipartContent(req)) {
            Map<String, Parameter> parameters = new HashMap<String, Parameter>();

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

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

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

                for (FileItem item : items) {
                    String fieldName = item.getFieldName();

                    if (item.isFormField()) {
                        String fieldValue = item.getString();

                        if (!parameters.containsKey(fieldName)) {
                            parameters.put(fieldName, new BasicParameter());
                        }

                        ((BasicParameter) parameters.get(fieldName)).add(fieldValue);
                    } else if (!item.isFormField() && item.getSize() > 0) {
                        parameters.put(fieldName, new MultipartFileParameter(item));
                    }
                }

                return parameters;
            } catch (FileUploadException e) {
                // Change the exception type
                throw new RuntimeException(e);
            }
        } else {
            return this.getParameterMap(req.getParameterMap());
        }
    }
}

From source file:edu.byui.fb.AddImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*www  . j  a  v a2  s  .  c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get the DataBaseHandler
    DataBaseHandler dbh = DataBaseHandler.getInstance();

    // Get information about the user currently logged in
    boolean logged = (boolean) request.getSession().getAttribute("logged");
    String username = (String) request.getSession().getAttribute("username");
    User user = dbh.getUser(username);

    // Are we currently logged in
    if (username != null && user != null && logged) {
        // Check to make sure the request is multipart
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                // Parse the request into FileItems
                List<FileItem> multipart = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);
                String title = "";
                InputStream imageInputStream = null;

                // Loop through each item
                for (FileItem item : multipart) {
                    // Are we dealing with a file or something different
                    if (!item.isFormField()) {
                        if (item.getFieldName().equals("image")) {
                            imageInputStream = item.getInputStream();
                        }
                    } else if (item.isFormField()) {
                        if (item.getFieldName().equals("title")) {
                            title = item.getString();
                        }
                    }
                }

                // Was there a title? If not, give a fake title
                if (title.equals("")) {
                    title = "No title";
                }

                // Set up the image and add to the DataBase.
                Image image = new Image(title, imageInputStream);
                dbh.addImage(image, user);
                request.setAttribute("imageAdded", true);
            } catch (FileUploadException ex) {
                Logger.getLogger(AddImage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } else {
        // Was there an error?
        request.setAttribute("addedError", true);
    }

    // Go to admin.jsp
    request.getRequestDispatcher("LoadImages?dest=admin.jsp").forward(request, response);
}

From source file:cc.aileron.wsgi.request.WsgiRequestParameterFactoryImpl.java

/**
 * @param request// ww  w . ja  v  a2 s  .c  o m
 * @param conv
 * @param upload
 * @return map
 * @throws FileUploadException
 */
private HashMap<String, Object> initMap(final Charset characterEncoding, final HttpServletRequest request,
        final ServletFileUpload upload) throws FileUploadException {
    final List<FileItem> params = Cast.<List<FileItem>>cast(upload.parseRequest(request));
    final HashMap<String, Object> result = new HashMap<String, Object>();
    final HashMap<String, List<Object>> tmp = new HashMap<String, List<Object>>();
    for (final FileItem item : params) {
        final String key = item.getFieldName();
        final List<Object> vals;
        {
            List<Object> t = tmp.get(key);
            if (t == null) {
                t = new SkipList<Object>();
                tmp.put(key, t);
            }
            vals = t;
        }
        if (item.isFormField()) {
            vals.add(new String(item.getString().getBytes(rawEncoding), characterEncoding));
        } else {
            vals.add(item);
        }
    }
    for (final Entry<String, List<Object>> e : tmp.entrySet()) {
        final String key = e.getKey();
        final List<Object> vals = e.getValue();
        result.put(key, vals.size() == 1 ? vals.get(0) : vals);
    }
    return result;
}

From source file:mx.org.cedn.avisosconagua.engine.processors.Pronostico.java

@Override
public void processForm(HttpServletRequest request, String[] parts, String currentId)
        throws ServletException, IOException {
    HashMap<String, String> parametros = new HashMap<>();
    boolean fileflag = false;
    AvisosException aex = null;//from www  .  j  a v  a2  s .  c  o  m
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MAX_SIZE);
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(MAX_SIZE);
            List<FileItem> items = upload.parseRequest(request);
            String filename = null;
            for (FileItem item : items) {
                if (!item.isFormField() && item.getSize() > 0) {
                    filename = processUploadedFile(item, currentId);
                    parametros.put(item.getFieldName(), filename);
                } else {
                    //System.out.println("item:" + item.getFieldName() + "=" + item.getString());
                    parametros.put(item.getFieldName(),
                            new String(item.getString().getBytes("ISO8859-1"), "UTF-8"));
                }
            }
        } catch (FileUploadException fue) {
            fue.printStackTrace();
            fileflag = true;
            aex = new AvisosException("El archivo sobrepasa el tamao de " + MAX_SIZE + " bytes", fue);
        }
    } else {
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            try {
                parametros.put(entry.getKey(),
                        new String(request.getParameter(entry.getKey()).getBytes("ISO8859-1"), "UTF-8"));
            } catch (UnsupportedEncodingException ue) {
                //No debe llegar a este punto
                assert false;
            }
        }
    }
    BasicDBObject anterior = (BasicDBObject) MongoInterface.getInstance().getAdvice(currentId).get(parts[3]);
    procesaImagen(parametros, anterior);
    MongoInterface.getInstance().savePlainData(currentId, parts[3], parametros);
    if (fileflag) {
        throw aex;
    }
}

From source file:com.fatih.edu.tr.NewTaskServlet.java

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

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;//from w w  w.  jav  a2 s  . c  om
    }

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

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

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

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

    TaskDao taskDao = new TaskDao();
    String title = "";
    String description = "";
    String due_date = "";
    String fileName = "";
    String filePath = "";
    //taskDao.addTask(title, description, due_date, "testfile","testdizi",1);

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

            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileName = new File(item.getName()).getName();
                filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                item.write(uploadedFile);
            } else {
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                if (fieldname.equals("title")) {
                    title = item.getString();
                } else if (fieldname.equals("description")) {
                    description = item.getString();

                } else if (fieldname.equals("due_date")) {
                    due_date = item.getString();
                } else {
                    System.out.println("Something goes wrong in form");
                }
            }

        }
        taskDao.addTask(title, description, due_date, fileName, filePath, 1);
        // displays done.jsp page after upload finished
        getServletContext().getRequestDispatcher("/done.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java

public void execute(ActionRequest actionRequest, ActionResponse actionResponse) {
    try {//from w  w  w  . j a  va 2 s.com
        sCheckPermissions(actionRequest);

        String portletId = "_" + PortalUtil.getPortletId(actionRequest) + "_";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(100 * 1024 * 1024);
        PortletFileUpload upload = new PortletFileUpload(factory);

        FileItem fileUploaded = null;
        List<FileItem> items = upload.parseRequest(actionRequest);
        for (FileItem fi : items) {
            if (fi.isFormField()) {
                actionRequest.setAttribute(fi.getFieldName(), fi.getString());
                if (fi.getFieldName().startsWith(portletId)) {
                    actionRequest.setAttribute(fi.getFieldName().substring(portletId.length()), fi.getString());
                }
            } else {
                fileUploaded = fi;
            }
        }

        String cmd = (String) actionRequest.getAttribute("cmd");
        String language = (String) actionRequest.getAttribute("language");
        String script = (String) actionRequest.getAttribute("script");
        String editorheight = (String) actionRequest.getAttribute("editorheight");
        String themesel = (String) actionRequest.getAttribute("themesel");
        if (language == null) {
            language = getDefaultLanguage();
        }
        if (script == null) {
            script = StringPool.BLANK;
        }
        actionResponse.setRenderParameter("language", language);
        actionResponse.setRenderParameter("script", script);
        actionResponse.setRenderParameter("editorheight", editorheight);
        actionResponse.setRenderParameter("themesel", themesel);

        if ("execute".equals(cmd)) {

            Map<String, Object> portletObjects = ScriptingHelperUtil.getPortletObjects(getPortletConfig(),
                    getPortletContext(), actionRequest, actionResponse);

            UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

            UnsyncPrintWriter unsyncPrintWriter = UnsyncPrintWriterPool.borrow(unsyncByteArrayOutputStream);

            portletObjects.put("out", unsyncPrintWriter);

            _log.info("Executing script");
            ScriptingUtil.exec(null, portletObjects, language, script, StringPool.EMPTY_ARRAY);
            unsyncPrintWriter.flush();
            actionResponse.setRenderParameter("script_output", unsyncByteArrayOutputStream.toString());
        } else if ("save".equals(cmd)) {
            String newscriptname = (String) actionRequest.getAttribute("newscriptname");
            if (newscriptname == null || newscriptname.trim().length() == 0) {
                actionResponse.setRenderParameter("script_trace", "No script name specified to save into!");
                SessionErrors.add(actionRequest, "error");
                return;
            }

            _log.info("Saving new script: " + newscriptname.trim());
            PortletPreferences prefs = actionRequest.getPreferences();
            prefs.setValue("savedscript." + newscriptname.trim(), script);
            prefs.setValue("lang." + newscriptname.trim(), language);
            prefs.store();
        } else if ("saveinto".equals(cmd)) {
            String scriptname = (String) actionRequest.getAttribute("savedscript");
            if (scriptname == null) {
                actionResponse.setRenderParameter("script_trace", "No script specified to save into!");
                SessionErrors.add(actionRequest, "error");
                return;
            }

            _log.info("Saving saved script: " + scriptname);
            PortletPreferences prefs = actionRequest.getPreferences();
            prefs.setValue("savedscript." + scriptname, script);
            prefs.setValue("lang." + scriptname, language);
            prefs.store();
        } else if ("loadfrom".equals(cmd)) {
            String scriptname = (String) actionRequest.getAttribute("savedscript");
            if (scriptname == null) {
                actionResponse.setRenderParameter("script_trace", "No script specified to load from!");
                SessionErrors.add(actionRequest, "error");
                return;
            }
            _log.info("Loading saved script: " + scriptname);
            PortletPreferences prefs = actionRequest.getPreferences();
            language = prefs.getValue("lang." + scriptname, getDefaultLanguage());
            script = prefs.getValue("savedscript." + scriptname, StringPool.BLANK);
            actionResponse.setRenderParameter("language", language);
            actionResponse.setRenderParameter("script", script);
        } else if ("delete".equals(cmd)) {
            String scriptname = (String) actionRequest.getAttribute("savedscript");
            if (scriptname == null) {
                actionResponse.setRenderParameter("script_trace", "No script specified to delete!");
                SessionErrors.add(actionRequest, "error");
                return;
            }
            _log.info("Deleting saved script: " + scriptname);
            PortletPreferences prefs = actionRequest.getPreferences();
            prefs.reset("savedscript." + scriptname);
            prefs.reset("lang." + scriptname);
            prefs.store();
        } else if ("import".equals(cmd)) {
            if (fileUploaded == null) {
                actionResponse.setRenderParameter("script_trace", "No file was uploaded for import!");
                SessionErrors.add(actionRequest, "error");
                return;
            }

            StringBuilder output = new StringBuilder();

            InputStream instream = fileUploaded.getInputStream();
            ZipInputStream zipstream = null;
            try {
                zipstream = new ZipInputStream(instream);
                ZipEntry entry = zipstream.getNextEntry();
                while (entry != null) {
                    String filename = entry.getName();
                    if (filename.contains("/")) {
                        int qs = filename.lastIndexOf("/");
                        if (qs != -1) {
                            filename = filename.substring(qs + 1);
                        }
                    }
                    if (filename.contains("\\")) {
                        int qs = filename.lastIndexOf("\\");
                        if (qs != -1) {
                            filename = filename.substring(qs + 1);
                        }
                    }

                    String ext = StringPool.BLANK;
                    if (filename.length() > 0) {
                        int qs = filename.lastIndexOf(".");
                        if (qs > 0) {
                            ext = filename.substring(qs + 1);
                            filename = filename.substring(0, qs);
                        }
                    }

                    String lang = resolveLanguage(ext);
                    String imscript = getStreamAsString(zipstream, "utf-8", false);

                    if (imscript != null && imscript.length() > 0) {
                        _log.info("Importing script \"" + filename + "\" of type " + lang);
                        output.append("Importing script \"" + filename + "\" of type " + lang + "\n");

                        PortletPreferences prefs = actionRequest.getPreferences();
                        prefs.setValue("savedscript." + filename, imscript);
                        prefs.setValue("lang." + filename, lang);
                        prefs.store();
                    }

                    entry = zipstream.getNextEntry();
                }

                actionResponse.setRenderParameter("script_output", output.toString());
            } finally {
                try {
                    if (zipstream != null) {
                        zipstream.close();
                    }
                } catch (Exception e) {
                }
                try {
                    if (instream != null) {
                        instream.close();
                    }
                } catch (Exception e) {
                }
            }

            _log.info(fileUploaded.getName());
        }
        SessionMessages.add(actionRequest, "success");
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.close();
        actionResponse.setRenderParameter("script_trace", sw.toString());
        _log.error(e);
        SessionErrors.add(actionRequest, e.toString());
    }
}

From source file:com.silverpeas.form.AbstractForm.java

/**
 * Gets the value of the specified parameter from the specified items.
 * @param items the items of the form embbeding multipart data.
 * @param parameterName the name of the parameter.
 * @param encoding the encoding at which the value must be in.
 * @return the value of the specified parameter in the given encoding. or null if no such
 * parameter is defined in this form./*from ww  w.j av  a  2 s  . c om*/
 * @throws UnsupportedEncodingException if the encoding at which the value should be in isn't
 * supported.
 */
private String getParameterValue(List<FileItem> items, String parameterName, String encoding)
        throws UnsupportedEncodingException {
    SilverTrace.debug("form", "AbstractForm.getParameterValue", "root.MSG_GEN_ENTER_METHOD",
            "parameterName = " + parameterName);
    FileItem item = getParameter(items, parameterName);
    if (item != null && item.isFormField()) {
        SilverTrace.debug("form", "AbstractForm.getParameterValue", "root.MSG_GEN_EXIT_METHOD",
                "parameterValue = " + item.getString());
        return item.getString(encoding);
    }
    return null;
}

From source file:com.meikai.common.web.servlet.FCKeditorConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 * //from w w w.  ja v  a 2  s  .  c  om
 * 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.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

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

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

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

    // edit check user uploader file size
    int contextLength = request.getContentLength();
    int fileSize = (int) (((float) contextLength) / ((float) (1024)));
    PrintWriter out = response.getWriter();

    if (fileSize < 30240) {

        String commandStr = request.getParameter("Command");
        String typeStr = request.getParameter("Type");
        String currentFolderStr = request.getParameter("CurrentFolder");
        String currentPath = baseDir + typeStr + "/" + dateCreated.substring(0, 4) + "/"
                + dateCreated.substring(5) + currentFolderStr;
        // create user dir
        makeDirectory(getServletContext().getRealPath("/"), currentPath);
        String currentDirPath = getServletContext().getRealPath(currentPath);
        // edit end ++++++++++++++++

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

        if (!commandStr.equals("FileUpload"))
            retVal = "203";
        else {
            DiskFileUpload upload = new DiskFileUpload();

            try {

                upload.setSizeMax(1 * 1024 * 1024); // ??,??: 
                upload.setSizeThreshold(4096); // ???,??: 
                upload.setRepositoryPath("c:/temp/"); // ?getSizeThreshold()? 
                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);
                if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, typeStr, ext)) {
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                        retVal = "201";
                        pathToSave = new File(currentDirPath, newName);
                        counter++;
                    }
                    uplFile.write(pathToSave);
                    // ?
                    if (logger.isInfoEnabled()) {
                        logger.info("...");
                    }
                } else {
                    retVal = "202";
                    if (debug)
                        System.out.println("Invalid file type: " + ext);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                retVal = "203";
            }
        }
    } else {
        retVal = "204";
    }
    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:importer.handler.post.ImporterPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request/*from w  w w.jav  a  2  s.co 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);
    }
}