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

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

Introduction

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

Prototype

void write(File file) throws Exception;

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:gov.nih.nci.caadapter.ws.AddNewScenario.java

/** **********************************************************
 *  doPost()//w ww  .  j  av  a  2s .c  o  m
 ************************************************************ */
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        /* disable security for caAdatper 4.3 release 03-31-2009
         HttpSession session = req.getSession(false);
                
          if(session==null)
          {
          res.sendRedirect("/caAdapterWS/login.do");
          return;
          }
                
          String user = (String) session.getAttribute("userid");
          System.out.println(user);
          AbstractSecurityDAO abstractDao= DAOFactory.getDAO();
          SecurityAccessIF getSecurityAccess = abstractDao.getSecurityAccess();
          Permissions perm = getSecurityAccess.getUserObjectPermssions(user, 1);
          System.out.println(perm);
          if (!perm.getCreate()){
          System.out.println("No create Permission for user" + user);
          res.sendRedirect("/caAdapterWS/permissionmsg.do");
          return;
          }
          */
        String name = "EMPTY";

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

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

        // Parse the request
        List /* FileItem */ items = upload.parseRequest(req);

        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                if (item.getFieldName().equals("MSName")) {
                    MSName = item.getString();
                    path = System.getProperty("gov.nih.nci.caadapter.path");
                    if (path == null)
                        path = ScenarioUtil.SCENARIO_HOME;
                    File scnHome = new File(path);
                    if (!scnHome.exists())
                        scnHome.mkdir();
                    path = path + "/";
                    System.out.println(path);
                    boolean exists = (new File(path + MSName)).exists();
                    if (exists) {
                        System.out.println("Scenario exists, overwriting ... ...");
                        String errMsg = "Scenario exists, not able to save:" + MSName;
                        req.setAttribute("rtnMessage", errMsg);
                        res.sendRedirect("/caAdapterWS/errormsg.do");
                        return;
                    } else {
                        boolean success = (new File(path + MSName)).mkdir();
                        if (!success) {
                            System.out.println("New scenario, Creating ... ...");
                        }
                    }

                }
            } else {
                System.out.println(item.getFieldName());
                name = item.getFieldName();

                String filePath = item.getName();
                String fileName = extractOriginalFileName(filePath);
                System.out.println("AddNewScenario.doPost()..original file Name:" + fileName);
                if (fileName == null || fileName.equals(""))
                    continue;
                String uploadedFilePath = path + MSName + "/" + fileName;
                System.out.println("AddNewScenario.doPost()...write data to file:" + uploadedFilePath);
                File uploadedFile = new File(uploadedFilePath);
                if (name.equals("mappingFileName")) {
                    String uploadedMapBak = uploadedFilePath + ".bak";
                    //write bak of Mapping file
                    item.write(new File(uploadedMapBak));
                    updateMapping(uploadedMapBak);
                } else
                    item.write(uploadedFile);
            }
        }
        ScenarioUtil.addNewScenarioRegistration(MSName);
        res.sendRedirect("/caAdapterWS/success.do");

    } catch (NullPointerException ne) {
        System.out.println("Error in doPost: " + ne);
        req.setAttribute("rtnMessage", ne.getMessage());
        res.sendRedirect("/caAdapterWS/errormsg.do");
    } catch (Exception e) {
        System.out.println("Error in doPost: " + e);
        req.setAttribute("rtnMessage", e.getMessage());
        res.sendRedirect("/caAdapterWS/error.do");
    }
}

From source file:co.com.rempe.impresiones.negocio.servlets.SubirArchivosServlet.java

private Respuesta subirArchivo(HttpServletRequest request) throws FileUploadException, Exception {
    Respuesta respuesta = new Respuesta();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    // req es la HttpServletRequest que recibimos del formulario.
    // Los items obtenidos sern cada uno de los campos del formulario,
    // tanto campos normales como ficheros subidos.
    //        System.out.println("Items-------");
    List items = upload.parseRequest(request);
    System.out.println(items);/* www.j  a v a  2 s  .  com*/

    //        System.out.println("Request-----------------");
    System.out.println(request);
    // Se recorren todos los items, que son de tipo FileItem
    for (Object item : items) {
        FileItem uploaded = (FileItem) item;
        // Hay que comprobar si es un campo de formulario. Si no lo es, se guarda el fichero
        // subido donde nos interese
        //            System.out.println("Item---------------");
        System.out.println(uploaded.isFormField());
        if (!uploaded.isFormField()) {
            // No es campo de formulario, guardamos el fichero en algn sitio

            //El sisguiente bloque simplemente es para divorciar el nombre del archivo de las rutas
            //posibles que pueda traernos el getName() sobre el objeto de  la clase FileItem,
            //pues he descuvierto que el explorer especificamente es el nico que enva
            //la ruta adjuntada al nombre, por lo cual es importante corregirlo.
            String nombreArchivo = uploaded.getName();
            String cadena = nombreArchivo;
            System.out.println(cadena);
            while (cadena.contains("\\")) {
                cadena = cadena.replace("\\", "&");
            }
            //                System.out.println(cadena);
            String[] ruta = cadena.split("&");
            for (int i = 0; i < ruta.length; i++) {
                String string = ruta[i];
                System.out.println(string);
            }
            nombreArchivo = ruta[ruta.length - 1];
            //                System.out.println("Ruta archivo: " + nombreArchivo);
            //Fin correccin nombre.

            String nombreArchivoEscrito = System.currentTimeMillis() + "-" + nombreArchivo;
            String rutaEscritura = new File(request.getRealPath("archivos-subidos"), nombreArchivoEscrito)
                    .toString();
            File fichero = new File(rutaEscritura);

            ArchivosAdjuntos archivo = new ArchivosAdjuntos();
            archivo.setNombreArchivo(nombreArchivo);
            archivo.setRutaArchivo(rutaEscritura);
            archivo.setTamanioArchivo(uploaded.getSize());
            if (nombreArchivo.endsWith(".pdf") || nombreArchivo.endsWith(".png")
                    || nombreArchivo.endsWith(".jpg") || nombreArchivo.endsWith(".bmp")
                    || nombreArchivo.endsWith(".svg")) {
                //                    System.out.println("Archivo subido: " + uploaded.getName());
                uploaded.write(fichero);
                respuesta.setCodigo(1);
                respuesta.setDatos(archivo);
                respuesta.setMensaje("Se ha subido exitosamente el archivo: " + uploaded.getName());
            } else {
                respuesta.setCodigo(0);
                respuesta.setDatos(archivo);
                respuesta.setMensaje("El formato del archivo " + nombreArchivo + " es invalido!");
            }
        }
        //            else {
        //                // es un campo de formulario, podemos obtener clave y valor
        //                String key = uploaded.getFieldName();
        //                String valor = uploaded.getString();
        //                System.out.println("Archivo subido: " + key);
        //            }
    }
    return respuesta;
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.filterConfiguration.FilterConfigurationImportHandler.java

/**
 * Upload the properties file to FilterConfigurations/import folder
 * /*from  w  w  w . j  a v a2  s  .co m*/
 * @param request
 */
private File uploadFile(HttpServletRequest request) {
    File f = null;
    try {
        String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight"
                + File.separator + "FilterConfigurations" + File.separator + "import";
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (!item.isFormField()) {
                    String filePath = item.getName();
                    if (filePath.contains(":")) {
                        filePath = filePath.substring(filePath.indexOf(":") + 1);
                    }
                    String originalFilePath = filePath.replace("\\", File.separator).replace("/",
                            File.separator);
                    String fileName = tmpDir + File.separator + originalFilePath;
                    f = new File(fileName);
                    f.getParentFile().mkdirs();
                    item.write(f);
                }
            }
        }
        return f;
    } catch (Exception e) {
        logger.error("File upload failed.", e);
        return null;
    }
}

From source file:com.mx.nibble.middleware.web.util.FileUploadOLD.java

public String execute() throws Exception {

    //ActionContext ac = invocation.getInvocationContext();

    HttpServletResponse response = ServletActionContext.getResponse();

    // MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest());
    HttpServletRequest multipartRequest = ServletActionContext.getRequest();

    List<FileItem> items2 = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartRequest);
    System.out.println("TAMAO ITEMS " + items2.size());
    System.out.println("Check that we have a file upload request");
    boolean isMultipart = ServletFileUpload.isMultipartContent(multipartRequest);
    System.out.println("isMultipart: " + isMultipart);

    String ourTempDirectory = "/opt/erp/import/obras/";

    byte[] cr = { 13 };
    byte[] lf = { 10 };
    String CR = new String(cr);
    String LF = new String(lf);
    String CRLF = CR + LF;/* www. j av a 2s  . c o m*/
    System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF);

    //Initialization for chunk management.
    boolean bLastChunk = false;
    int numChunk = 0;

    //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL
    boolean generateError = false;
    boolean generateWarning = false;
    boolean sendRequest = false;

    response.setContentType("text/plain");

    java.util.Enumeration<String> headers = multipartRequest.getHeaderNames();
    System.out.println("[parseRequest.jsp]  ------------------------------ ");
    System.out.println("[parseRequest.jsp]  Headers of the received request:");
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        System.out.println("[parseRequest.jsp]  " + header + ": " + multipartRequest.getHeader(header));
    }
    System.out.println("[parseRequest.jsp]  ------------------------------ ");

    try {
        System.out.println(" Get URL Parameters.");
        Enumeration paraNames = multipartRequest.getParameterNames();
        System.out.println("[parseRequest.jsp]  ------------------------------ ");
        System.out.println("[parseRequest.jsp]  Parameters: ");
        String pname;
        String pvalue;
        while (paraNames.hasMoreElements()) {
            pname = (String) paraNames.nextElement();
            pvalue = multipartRequest.getParameter(pname);
            System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue);
            if (pname.equals("jufinal")) {
                System.out.println("pname.equals(\"jufinal\")");
                bLastChunk = pvalue.equals("1");
            } else if (pname.equals("jupart")) {
                System.out.println("pname.equals(\"jupart\")");
                numChunk = Integer.parseInt(pvalue);
            }

            //For debug convenience, putting error=true as a URL parameter, will generate an error
            //in this response.
            if (pname.equals("error") && pvalue.equals("true")) {
                generateError = true;
            }

            //For debug convenience, putting warning=true as a URL parameter, will generate a warning
            //in this response.
            if (pname.equals("warning") && pvalue.equals("true")) {
                generateWarning = true;
            }

            //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content
            //into the response of this page.
            if (pname.equals("sendRequest") && pvalue.equals("true")) {
                sendRequest = true;
            }

        }
        System.out.println("[parseRequest.jsp]  ------------------------------ ");

        int ourMaxMemorySize = 10000000;
        int ourMaxRequestSize = 2000000000;

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //The code below is directly taken from the jakarta fileupload common classes
        //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/
        ///////////////////////////////////////////////////////////////////////////////////////////////////////

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

        // Set factory constraints
        factory.setSizeThreshold(ourMaxMemorySize);
        factory.setRepository(new File(ourTempDirectory));

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

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

        // Parse the request
        if (sendRequest) {
            //For debug only. Should be removed for production systems. 
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
            System.out.println("[parseRequest.jsp] Sending the received request content: ");
            InputStream is = multipartRequest.getInputStream();
            int c;
            while ((c = is.read()) >= 0) {
                System.out.write(c);
            } //while
            is.close();
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
        } else if (!multipartRequest.getContentType().startsWith("multipart/form-data")) {
            System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is "
                    + multipartRequest.getContentType());
        } else {
            List /* FileItem */ items = upload.parseRequest(multipartRequest);
            // Process the uploaded items
            Iterator iter = items.iterator();
            FileItem fileItem;
            File fout;
            System.out.println("[parseRequest.jsp]  Let's read the sent data   (" + items.size() + " items)");
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();

                if (fileItem.isFormField()) {
                    System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = "
                            + fileItem.getString());

                    //If we receive the md5sum parameter, we've read finished to read the current file. It's not
                    //a very good (end of file) signal. Will be better in the future ... probably !
                    //Let's put a separator, to make output easier to read.
                    if (fileItem.getFieldName().equals("md5sum[]")) {
                        System.out.println("[parseRequest.jsp]  ------------------------------ ");
                    }
                } else {
                    //Ok, we've got a file. Let's process it.
                    //Again, for all informations of what is exactly a FileItem, please
                    //have a look to http://jakarta.apache.org/commons/fileupload/
                    //
                    System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName());
                    System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName());
                    System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType());
                    System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize());
                    //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number.
                    String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : "");
                    fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName());
                    System.out.println("[parseRequest.jsp] File Out: " + fout.toString());
                    System.out.println(" write the file");
                    fileItem.write(fout);

                    //////////////////////////////////////////////////////////////////////////////////////
                    System.out.println(
                            " Chunk management: if it was the last chunk, let's recover the complete file");
                    System.out.println(" by concatenating all chunk parts.");
                    //
                    if (bLastChunk) {
                        System.out.println(
                                "[parseRequest.jsp]  Last chunk received: let's rebuild the complete file ("
                                        + fileItem.getName() + ")");
                        //First: construct the final filename.
                        FileInputStream fis;
                        FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName());
                        int nbBytes;
                        byte[] byteBuff = new byte[1024];
                        String filename;
                        for (int i = 1; i <= numChunk; i += 1) {
                            filename = fileItem.getName() + ".part" + i;
                            System.out.println("[parseRequest.jsp] " + "  Concatenating " + filename);
                            fis = new FileInputStream(ourTempDirectory + filename);
                            while ((nbBytes = fis.read(byteBuff)) >= 0) {
                                //out.println("[parseRequest.jsp] " + "     Nb bytes read: " + nbBytes);
                                fos.write(byteBuff, 0, nbBytes);
                            }
                            fis.close();
                        }
                        fos.close();
                    }

                    // End of chunk management
                    //////////////////////////////////////////////////////////////////////////////////////

                    fileItem.delete();
                }
            } //while
        }

        if (generateWarning) {
            System.out.println("WARNING: just a warning message.\\nOn two lines!");
        }

        System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :");

        //Let's wait a little, to simulate the server time to manage the file.
        Thread.sleep(500);

        //Do you want to test a successful upload, or the way the applet reacts to an error ?
        if (generateError) {
            System.out.println(
                    "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!");
        } else {
            System.out.println("SUCCESS");
            //out.println("                        <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>");
        }

        System.out.println("[parseRequest.jsp] " + "End of server treatment ");

    } catch (Exception e) {
        System.out.println("");
        System.out.println("ERROR: Exception e = " + e.toString());
        System.out.println("");
    }
    return SUCCESS;
}

From source file:com.wellmail.servlet.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from  w w w.  j av  a  2s. c  o m
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    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");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");

            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                filename = UUID.randomUUID().toString() + "." + extension;

                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);

                //20k
                else if (uplFile.getSize() > 100 * 1024) {
                    ur = new UploadResponse(204);
                }

                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:com.darksky.seller.SellerServlet.java

/**
 *   //from  w  w  w  .  ja  v  a 2 s .  co m
 * ?
 * @param request
 * @param response
 * @throws Exception
 */
public void modifyShopInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println();
    System.out.println("--------------------shop modify info-----------------");
    /* ? */
    String sellerID = Seller.getSellerID();

    /* ? */

    String shopID = Shop.getShopID();
    String shopName = null;
    String shopTel = null;
    String shopIntroduction = null;
    String Notice = null;
    String shopAddress = null;
    String shopPhoto = null;

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
    ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
    // ?
    sfu.setHeaderEncoding("UTF-8");
    // ?2M
    sfu.setFileSizeMax(1024 * 1024 * 2);
    // ?10M
    sfu.setSizeMax(1024 * 1024 * 10);
    List<FileItem> itemList = sfu.parseRequest(request);

    List<FileItem> itemList2 = sfu2.parseRequest(request);

    FileItem a = null;

    for (FileItem fileItem : itemList) {

        if (!fileItem.isFormField()) {
            a = fileItem;

            System.out.println("QQQQQQQQQQQQQQQQ" + fileItem.toString() + "QQQQQQQQ");

        } else {
            String fieldName = fileItem.getFieldName();
            String value = fileItem.getString("utf-8");
            switch (fieldName) {
            case "shopName":
                shopName = value;
                break;
            case "shopTel":
                shopTel = value;
                break;
            case "shopIntroduction":
                shopIntroduction = value;
                break;
            case "Notice":
                Notice = value;
                break;
            case "shopPhoto":
                shopPhoto = value;
                break;
            case "shopAddress":
                shopAddress = value;
                break;

            default:
                break;
            }

        }

    }
    double randomNum = Math.random();
    shopPhoto = "image/" + shopID + "_" + randomNum + ".jpg";
    String savePath2 = getServletContext().getRealPath("");
    System.out.println("path2=" + savePath2);
    getDish(sellerID);

    String shopSql = null;
    if (a.getSize() != 0) {
        File file2 = new File(savePath2, shopPhoto);
        a.write(file2);

        shopSql = "update shop set shopName='" + shopName + "' , shopTel='" + shopTel + "' , shopIntroduction='"
                + shopIntroduction + "' , Notice='" + Notice + "' , shopAddress='" + shopAddress
                + "',shopPhoto='" + shopPhoto + "' where shopID='" + shopID + "'";
    }

    else {

        shopSql = "update shop set shopName='" + shopName + "' , shopTel='" + shopTel + "' , shopIntroduction='"
                + shopIntroduction + "' , Notice='" + Notice + "' , shopAddress='" + shopAddress
                + "' where shopID='" + shopID + "'";
    }

    System.out.println("shopSql: " + shopSql);

    try {
        statement.executeUpdate(shopSql);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    getShop(Seller.getShopID());
    request.getSession().setAttribute("shop", Shop);

    System.out.println("--------------------shop modify info-----------------");
    System.out.println();

    request.getRequestDispatcher(".jsp").forward(request, response);
}

From source file:Controle.Controle_foto.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    ArrayList<Object> obj = new ArrayList<Object>();
    Mensagem msg = new Mensagem();
    Gson gson = new Gson();
    PrintWriter out = response.getWriter();

    Foto foto = new Foto();
    FotoDAO fotoDAO = new FotoDAO();

    System.out.println("teste");
    if (isMultipart) {
        System.out.println("teste2");
        FileItemFactory factory = new DiskFileItemFactory();
        System.out.println("teste3");
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {//from w ww  .  ja v a2s  . c o  m
            System.out.println("teste4");
            List itens = upload.parseRequest(request);
            Iterator iterator = itens.iterator();
            String id = "";
            String legenda = "";
            id = request.getParameter("id");
            //                
            //                if(id.equals("null")){
            //                    System.out.println("sem id da foto");
            //                }else{
            //                    System.out.println("com id da foto");
            //                }

            System.out.println("id da foto: " + request.getParameter("id"));

            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();

                if (!item.isFormField()) {
                    String nomeArquivo = item.getName();
                    String extensao = "";

                    System.out.println(nomeArquivo);
                    int cont = 4;
                    for (int i = 0; i <= 3; i++) {
                        extensao += nomeArquivo.charAt(nomeArquivo.length() - cont);
                        cont = cont - 1;
                    }
                    Random rdm = new Random();
                    int n = rdm.nextInt(99999);
                    nomeArquivo = id + n + extensao;

                    System.out.println(nomeArquivo);
                    String diretorio = getServletContext().getRealPath("/");
                    File destino = new File(diretorio + "/segura/img");
                    System.out.println(destino);

                    //apagar arquivo antigo.

                    foto = fotoDAO.buscarPorId(Integer.parseInt(id));

                    if (foto.getId() <= 0) {
                        throw new Exception("Foto no encontrada!!!!");
                    } else {
                        File arquivoAntigo = new File(diretorio + "/" + foto.getEndereco());
                        System.out.println("Endereo da imagem antiga !!!!!!!!!" + foto.getEndereco());
                        if (!foto.getEndereco().equals("segura/default/sem_foto.jpg")) {
                            boolean bool = arquivoAntigo.delete();
                            System.out.println("arquivo apagado? " + bool);
                            System.out.println("O seguinte arquivo antigo foi apagardo!!!!!!!!!"
                                    + arquivoAntigo.getAbsolutePath());
                        }
                        foto.setEndereco("/segura/img/" + nomeArquivo);
                        foto.setLegenda(legenda);
                        fotoDAO.atualizar(foto);
                    }

                    //                        if (!destino.exists()) {
                    //                            boolean status = destino.mkdirs();
                    //
                    //                        }
                    File arquivoRecebido = new File(destino + "/" + nomeArquivo);
                    System.out.println(arquivoRecebido.getAbsolutePath());

                    item.write(arquivoRecebido);

                } else {
                    if (!item.getFieldName().equals("legenda")) {
                        id = item.getString();
                    } else {
                        legenda = item.getString();
                    }

                    System.out.println("Nome do campo !!!" + item.getFieldName());
                    System.out.println("Olha o valor do id  !!!" + item.getString());

                }

            }
            msg.setMensagem("Cadastrado com sucesso!!!!");
            msg.setTipo(1);
            obj.add(msg);
        } catch (FileUploadException e) {
            e.printStackTrace();
            System.out.println("Erro!!" + e.getMessage());
            msg.setMensagem("Erro!!" + e.getMessage());
            msg.setTipo(2);
            obj.add(msg);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Erro!!" + e.getMessage());
            msg.setMensagem("Erro!!" + e.getMessage());
            msg.setTipo(2);
            obj.add(msg);
        } finally {
            out.printf(gson.toJson(obj));
        }
    } else {
        System.out.println("deu ruim no multpart");
    }
}

From source file:net.fckeditor.connector.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //w  w w .  j a  v a  2s .c  o  m
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    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");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            // TODO ############???##############
            upload.setHeaderEncoding("UTF-8");

            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                // TODO ############??? ############
                filename = UUID.randomUUID().toString() + "." + extension;

                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                } else if (uplFile.getSize() >= MAX_FILESIZE) {
                    ur = new UploadResponse(204);
                } else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);
                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }
    }
    out.print(ur);
    out.flush();
    out.close();
    logger.debug("Exiting Connector#doPost");
}

From source file:com.wfms.common.web.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from  w ww .j  av  a 2  s. c  om
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    //response.setCharacterEncoding("UTF-8");
    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");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                //add code
                filename = UUID.randomUUID().toString() + "." + extension;
                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                }
                //add conde to validate file size
                else if (uplFile.getSize() > 1024 * 1024) {
                    ur = new UploadResponse(204);
                } else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:com.nartex.FileManager.java

public JSONObject add() {
    JSONObject fileInfo = null;/*from   w  ww  .j  ava  2s . c  o m*/
    Iterator it = this.files.iterator();
    String mode = "";
    String currentPath = "";
    if (!it.hasNext()) {
        this.error(lang("INVALID_FILE_UPLOAD"));
    } else {
        String allowed[] = { ".", "-" };
        FileItem item = null;
        String fileName = "";
        try {
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equals("mode")) {
                        mode = item.getString();
                        if (!mode.equals("add")) {
                            this.error(lang("INVALID_FILE_UPLOAD"));
                        }
                    } else if (item.getFieldName().equals("currentpath")) {
                        currentPath = item.getString();
                    }
                } else if (item.getFieldName().equals("newfile")) {
                    fileName = item.getName();
                    // strip possible directory (IE)
                    int pos = fileName.lastIndexOf(File.separator);
                    if (pos > 0)
                        fileName = fileName.substring(pos + 1);
                    boolean error = false;
                    long maxSize = 0;
                    if (config.getProperty("upload-size") != null) {
                        maxSize = Integer.parseInt(config.getProperty("upload-size"));
                        if (maxSize != 0 && item.getSize() > (maxSize * 1024 * 1024)) {
                            this.error(sprintf(lang("UPLOAD_FILES_SMALLER_THAN"), maxSize + "Mb"));
                            error = true;
                        }
                    }
                    if (!error) {
                        if (!isImage(fileName) && (config.getProperty("upload-imagesonly") != null
                                && config.getProperty("upload-imagesonly").equals("true")
                                || this.params.get("type") != null
                                        && this.params.get("type").equals("Image"))) {
                            this.error(lang("UPLOAD_IMAGES_ONLY"));
                        } else {
                            fileInfo = new JSONObject();
                            LinkedHashMap<String, String> strList = new LinkedHashMap<String, String>();
                            strList.put("fileName", fileName);
                            fileName = (String) cleanString(strList, allowed).get("fileName");

                            if (config.getProperty("upload-overwrite").equals("false")) {
                                fileName = this.checkFilename(this.documentRoot + currentPath, fileName, 0);
                            }

                            File saveTo = new File(this.documentRoot + currentPath + fileName);
                            item.write(saveTo);

                            fileInfo.put("Path", currentPath);
                            fileInfo.put("Name", fileName);
                            fileInfo.put("Error", "");
                            fileInfo.put("Code", 0);
                        }
                    }
                }
            }
        } catch (Exception e) {
            this.error(lang("INVALID_FILE_UPLOAD"));
        }
    }
    return fileInfo;

}