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:com.enonic.vertical.adminweb.AdminHandlerBaseServlet.java

public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    fileUpload = new DiskFileUpload();
    fileUpload.setHeaderEncoding("UTF-8");
    fileUpload.setSizeMax(verticalProperties.getMultiPartRequestMaxSize());
    fileUpload.setSizeThreshold(64000);/*from   ww  w  . j  ava2s .  c  o  m*/

    // Parameters for the mail sent to users when generating a new password:
    SMTP_HOST = verticalProperties.getMailSmtpHost();
    if (SMTP_HOST == null) {
        SMTP_HOST = "mail.enonic.com";
    }
}

From source file:fsi_admin.JAwsS3Conn.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ERROR = null, codErr = null;

    try {/*from   ww  w. ja v a  2  s. co m*/
        Properties parametros = new Properties();
        Vector archivos = new Vector();
        DiskFileUpload fu = new DiskFileUpload();
        List items = fu.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField())
                parametros.put(item.getFieldName(), item.getString());
            else
                archivos.addElement(item);
        }

        if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null
                || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null
                || parametros.getProperty("ACTION") == null) {
            System.out.println("No recibi parametros de conexin antes del archivo");
            ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD,ACTION) antes del archivo";
            codErr = "3";
            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
        }

        //Hasta aqui se han enviado todos los parametros ninguno nulo
        if (ERROR == null) {
            StringBuffer msj = new StringBuffer(), S3BUKT = new StringBuffer(), S3USR = new StringBuffer(),
                    S3PASS = new StringBuffer();
            MutableBoolean COBRAR = new MutableBoolean(false);
            MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0);
            // Primero obtiene info del S3
            if (!obtenInfoAWSS3(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"),
                    parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), S3BUKT, S3USR, S3PASS,
                    msj, COSTO, SALDO, COBRAR)) {
                System.out.println("El usuario y contrasea de servicio estan mal");
                ERROR = msj.toString();
                codErr = "2";
                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                        parametros.getProperty("PASSWORD"), request, ERROR, 2);

            } else {
                AWSCredentials credentials = new BasicAWSCredentials(S3USR.toString(), S3PASS.toString());
                AmazonS3 s3 = new AmazonS3Client(credentials);
                Region usWest2 = Region.getRegion(Regions.US_WEST_2);
                s3.setRegion(usWest2);
                //System.out.println("AwsConn:" + parametros.getProperty("NOMBRE") + ":parametros.getProperty(NOMBRE)");
                String nombre = parametros.getProperty("SERVER") + parametros.getProperty("DATABASE")
                        + parametros.getProperty("ID_MODULO") + parametros.getProperty("OBJIDS")
                        + parametros.getProperty("IDSEP") + parametros.getProperty("NOMBRE");
                //System.out.println("AwsConn_Nombre:" + nombre + ":nombre");

                if (parametros.getProperty("ACTION").equals("SUBIR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));
                    Double TAMBITES = new Double(Double.parseDouble(parametros.getProperty("TAMBITES")));

                    if (COBRAR.booleanValue() && SALDO
                            .doubleValue() < (COSTO.doubleValue() * (((TOTBITES + TAMBITES) / 1024) / 1024))) {
                        System.out
                                .println("El servicio S3 de subida tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de subida tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!subirArchivo(msj, s3, S3BUKT.toString(), nombre, archivos)) {
                            System.out.println("No se permiti subir el archivo al s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else {
                            ingresarRegistroExitoso(parametros.getProperty("SERVER"),
                                    parametros.getProperty("DATABASE"), parametros.getProperty("ID_MODULO"),
                                    parametros.getProperty("OBJIDS"), parametros.getProperty("IDSEP"),
                                    parametros.getProperty("NOMBRE"), parametros.getProperty("TAMBITES"));
                        }
                    }

                } else if (parametros.getProperty("ACTION").equals("ELIMINAR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));

                    if (COBRAR.booleanValue()
                            && SALDO.doubleValue() < (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))) {
                        System.out
                                .println("El servicio S3 de borrado tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de borrado tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!eliminarArchivo(msj, s3, S3BUKT.toString(), nombre)) {
                            System.out.println("No se permiti eliminar el archivo del s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else {
                            eliminarRegistroExitoso(parametros.getProperty("SERVER"),
                                    parametros.getProperty("DATABASE"), parametros.getProperty("ID_MODULO"),
                                    parametros.getProperty("OBJIDS"), parametros.getProperty("IDSEP"),
                                    parametros.getProperty("NOMBRE"));
                        }
                    }
                } else if (parametros.getProperty("ACTION").equals("DESCARGAR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));
                    //System.out.println("COBRAR: " + COBRAR.booleanValue() + " SALDO: " + SALDO.doubleValue() + " COSTO: " + COSTO.doubleValue() + " TOTBITES: " + TOTBITES + " TOTMB: " + ((TOTBITES / 1024) / 1024) + " RES: " + (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024)));
                    if (COBRAR.booleanValue()
                            && SALDO.doubleValue() < (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))) {
                        System.out.println(
                                "El servicio S3 de descarga tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de descarga tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!descargarArchivo(response, msj, s3, S3BUKT.toString(), nombre,
                                parametros.getProperty("NOMBRE"))) {
                            System.out.println("No se permiti descargar el archivo del s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else
                            return;
                    }
                }

                if (ERROR == null) {
                    //Devuelve la respuesta al cliente
                    Element S3 = new Element("S3");
                    S3.setAttribute("Archivo", nombre);
                    S3.setAttribute("MsjError", "");
                    Document Reporte = new Document(S3);

                    Format format = Format.getPrettyFormat();
                    format.setEncoding("utf-8");
                    format.setTextMode(TextMode.NORMALIZE);
                    XMLOutputter xmlOutputter = new XMLOutputter(format);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    xmlOutputter.output(Reporte, out);

                    byte[] data = out.toByteArray();
                    ByteArrayInputStream istream = new ByteArrayInputStream(data);

                    String destino = "Archivo.xml";
                    JBajarArchivo fd = new JBajarArchivo();
                    fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml",
                            data.length, destino);

                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        ERROR = "ERROR DE EXCEPCION EN SERVIDOR AWS S3: " + e.getMessage();
    }

    //Genera el archivo XML de error para ser devuelto al Servidor
    if (ERROR != null) {
        Element SIGN_ERROR = new Element("SIGN_ERROR");
        SIGN_ERROR.setAttribute("CodError", codErr);
        SIGN_ERROR.setAttribute("MsjError", ERROR);
        Document Reporte = new Document(SIGN_ERROR);

        Format format = Format.getPrettyFormat();
        format.setEncoding("utf-8");
        format.setTextMode(TextMode.NORMALIZE);
        XMLOutputter xmlOutputter = new XMLOutputter(format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        xmlOutputter.output(Reporte, out);

        byte[] data = out.toByteArray();
        ByteArrayInputStream istream = new ByteArrayInputStream(data);

        String destino = "SIGN_ERROR.xml";
        JBajarArchivo fd = new JBajarArchivo();
        fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length,
                destino);

    }

}

From source file:com.krawler.esp.handlers.genericFileUpload.java

public void doPostCompay(List fileItems, String filename, String destinationDirectory) {
    File destDir = new File(destinationDirectory);
    Ext = "";/*from  w  w  w  . j  av a  2 s. com*/
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setSizeThreshold(4096);
    fu.setRepositoryPath(destinationDirectory);
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
            String fileName = null;
            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                if (fileName.contains("."))
                    Ext = fileName.substring(fileName.lastIndexOf("."));
                if (fi.getSize() != 0) {
                    this.isUploaded = true;
                    File uploadFile = new File(destinationDirectory + "/" + "temp_" + filename + Ext);
                    fi.write(uploadFile);
                    imgResizeCompany(destinationDirectory + "/" + "temp_" + filename + Ext, 0, 0,
                            destinationDirectory + "/original_" + filename, true);
                    imgResizeCompany(destinationDirectory + "/" + "temp_" + filename + Ext, 130, 25,
                            destinationDirectory + "/" + filename, false);
                    //                  imgResize(destinationDirectory + "/" + filename + Ext,
                    //                        0, 0, destinationDirectory + "/original_" + filename);
                    uploadFile.delete();
                } else {
                    this.isUploaded = false;
                }
            } catch (Exception e) {
                this.ErrorMsg = "Problem occured while uploading logo";
                logger.warn(e.getMessage(), e);
            }
        }
    }
}

From source file:com.rapidsist.portal.cliente.editor.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 .  ja  va 2  s.c om*/
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println("PASO POR EL METODO doPost DEL SERVLET SimpleUploaderServlet");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

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

    String currentPath = baseDir + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);
    currentPath = request.getContextPath() + currentPath;

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

    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 = "";
            }
        } catch (Exception ex) {
            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();
}

From source file:cn.itcast.fredck.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./* w ww  . ja v a  2 s  .c  o  m*/
 *
 */
@Override
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 typeStr = request.getParameter("Type");

    String currentPath = baseDir + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);
    currentPath = request.getContextPath() + currentPath;

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

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

    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:com.tern.web.MultiPartEnabledRequest.java

private List uploadFiles(HttpServletRequest req) throws FileUploadException {
    DiskFileUpload upload = new DiskFileUpload();

    /*try /*from w ww.ja va 2 s .c om*/
    {
      upload.setSizeThreshold(res.getInteger("file.upload.size.threshold"));
    } 
    catch (MissingResourceException e)
    {
      // use defaults
    }*/

    try {
        upload.setSizeMax(MaxFileSize);
    } catch (MissingResourceException e) {
        // use defaults
    }

    /*try 
    {
      upload.setRepositoryPath(res.getString("file.upload.repository"));
    } 
    catch (MissingResourceException e) 
    {
      // use defaults
    }*/

    List all = new DiskFileUpload().parseRequest(req);
    return all;
}

From source file:com.fredck.FCKeditor.uploader.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 * /* w  w w  .  j  a v a 2 s . com*/
 * 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.
 * 
 */
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 typeStr = request.getParameter("Type");
    String currentPath = baseDir + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);
    currentPath = request.getContextPath() + currentPath;
    if (debug) {
        System.out.println(currentDirPath);
    }
    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";
    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";
    }

    System.out.println("111111222111111111");
    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:info.magnolia.cms.filters.CommonsFileUploadMultipartRequestFilter.java

/**
 * Create a new <code>DiskFileUpload</code>.
 *///  w w  w  . ja  va 2s .c om
private DiskFileUpload newDiskFileUpload() {
    DiskFileUpload upload = new DiskFileUpload();
    upload.setSizeMax(this.maxFileSize);
    upload.setRepositoryPath(Path.getTempDirectoryPath());

    return upload;
}

From source file:com.meikai.common.web.servlet.FCKeditorUploadServlet.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 w w w  .  j a  va2  s.  co  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();
    // edit check user uploader file size
    int contextLength = request.getContentLength();
    int fileSize = (int) (((float) contextLength) / ((float) (1024)));

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

    if (fileSize < 30240) {

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

        String currentPath = "";
        String currentDirPath = getServletContext().getRealPath(currentPath);
        currentPath = request.getContextPath() + currentPath;
        // edit end ++++++++++++++++   
        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 = FckeditorUtil.getNameWithoutExtension(fileName);
                String ext = FckeditorUtil.getExtension(fileName);
                File pathToSave = new File(currentDirPath, fileName);
                fileUrl = currentPath + "/" + fileName;
                if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, 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);

                    // ?
                    if (logger.isInfoEnabled()) {
                        logger.info("...");
                    }
                } 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";
        }

    } else {
        retVal = "204";
    }
    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:com.useeasy.auction.util.upload.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 * /*from   w  w w .ja v  a2s .  co m*/
 * 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.
 * 
 */
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 typeStr = request.getParameter("Type");

    String currentPath = baseDir + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);
    currentPath = request.getContextPath() + currentPath;

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

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

    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);
            if (extIsAllowed(typeStr, ext)) {
                SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmssSSS");
                newName = format.format(new Date()) + String.valueOf(((int) (Math.random() * 100000))) + "."
                        + ext;
                fileUrl = currentPath + "/" + newName;
                pathToSave = new File(currentDirPath, newName);
                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 ---");

}