Example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest.

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:com.dotmarketing.portlets.cmsmaintenance.ajax.IndexAjaxAction.java

public void restoreIndex(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DotDataException {
    try {/*  w w w .  j a v  a 2 s .co  m*/
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);

        String indexToRestore = null;
        boolean clearBeforeRestore = false;
        String aliasToRestore = null;
        File ufile = null;
        boolean isFlash = false;
        for (FileItem it : items) {
            if (it.getFieldName().equalsIgnoreCase("indexToRestore")) {
                indexToRestore = it.getString().trim();
            } else if (it.getFieldName().equalsIgnoreCase("aliasToRestore")) {
                aliasToRestore = it.getString().trim();
            } else if (it.getFieldName().equalsIgnoreCase("uploadedfiles[]")
                    || it.getFieldName().equals("uploadedfile")
                    || it.getFieldName().equalsIgnoreCase("uploadedfileFlash")) {
                isFlash = it.getFieldName().equalsIgnoreCase("uploadedfileFlash");
                ufile = File.createTempFile("indexToRestore", "idx");
                InputStream in = it.getInputStream();
                FileOutputStream out = new FileOutputStream(ufile);
                IOUtils.copyLarge(in, out);
                IOUtils.closeQuietly(out);
                IOUtils.closeQuietly(in);
            } else if (it.getFieldName().equalsIgnoreCase("clearBeforeRestore")) {
                clearBeforeRestore = true;
            }
        }

        if (LicenseUtil.getLevel() >= 200) {
            if (UtilMethods.isSet(aliasToRestore)) {
                String indexName = APILocator.getESIndexAPI()
                        .getAliasToIndexMap(APILocator.getSiteSearchAPI().listIndices()).get(aliasToRestore);
                if (UtilMethods.isSet(indexName))
                    indexToRestore = indexName;
            } else if (!UtilMethods.isSet(indexToRestore)) {
                indexToRestore = APILocator.getIndiciesAPI().loadIndicies().site_search;
            }
        }

        if (ufile != null) {
            final boolean clear = clearBeforeRestore;
            final String index = indexToRestore;
            final File file = ufile;
            new Thread() {
                public void run() {
                    try {
                        if (clear)
                            APILocator.getESIndexAPI().clearIndex(index);
                        APILocator.getESIndexAPI().restoreIndex(file, index);
                        Logger.info(this, "finished restoring index " + index);
                    } catch (Exception ex) {
                        Logger.error(IndexAjaxAction.this, "Error restoring", ex);
                    }
                }
            }.start();

        }

        PrintWriter out = response.getWriter();
        if (isFlash) {
            out.println("response=ok");
        } else {
            response.setContentType("application/json");
            out.println("{\"response\":1}");
        }

    } catch (FileUploadException fue) {
        Logger.error(this, "Error uploading file", fue);
        throw new IOException(fue);
    }
}

From source file:controller.insertProduct.java

private void insertProduct(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    String productType = null;/*from  w  w w . ja v a  2 s. co m*/
    String resolution = null;
    String hdmi = null;
    String usb = null;
    String model = null;
    String size = null;
    String warranty = null;

    String productName = null;
    int price = 0;
    String description = null;
    Integer quantity = null;
    String produceID = null;
    String image = null;

    String uploadDirectory = "/Product/Images";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    File uploadDir;
    File storeFile;
    try {
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);
        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadDirectory + File.separator + fileName;
                    storeFile = new File(filePath);
                    item.write(storeFile);
                    image = produceID + "/" + fileName;
                    System.out.println(storeFile.getPath());
                } else {
                    switch (item.getFieldName()) {
                    case "productName":
                        productName = item.getString("UTF-8");
                        break;
                    case "produceID": {
                        produceID = item.getString("UTF-8");
                        uploadDir = new File(uploadPath + uploadDirectory + "/" + produceID);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdir();
                        }
                        uploadDirectory = uploadPath + uploadDirectory + "/" + produceID;
                        break;
                    }
                    case "price":
                        price = (Integer.parseInt(item.getString("UTF-8")));
                        break;
                    case "quantity":
                        quantity = (Integer.parseInt(item.getString("UTF-8")));
                        break;
                    case "productType":
                        productType = item.getString("UTF-8");
                        break;
                    case "resolution":
                        resolution = item.getString("UTF-8");
                        break;
                    case "hdmi":
                        hdmi = item.getString("UTF-8");
                        break;
                    case "usb":
                        usb = item.getString("UTF-8");
                        break;
                    case "Model":
                        model = item.getString("UTF-8");
                        break;
                    case "size":
                        size = item.getString("UTF-8");
                        break;
                    case "warranty":
                        warranty = item.getString("UTF-8");
                        break;
                    case "description": {
                        description = item.getString("UTF-8");
                        System.out.println(description);
                        break;
                    }
                    }
                }
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }

    @SuppressWarnings("null")
    ProductInfo prinfo = new ProductInfo(productType, resolution, hdmi, usb, model, size, warranty);
    Products product = new Products(productName, price, description, quantity, image, prinfo, produceID);

    if (ProductsDAO.insertProduct(product)) {
        out.print(
                "<center><b><font color='red'>thm thnh cng! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>");
    } else {
        out.print(
                "<center><b><font color='red'>Thm tht bi! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>");
    }
}

From source file:it.lufraproini.cms.servlet.Upload.java

private Map prendiInfo(HttpServletRequest request) throws FileUploadException {
    Map info = new HashMap();
    Map files = new HashMap();

    //riutilizzo codice prof. Della Penna per l'upload
    if (ServletFileUpload.isMultipartContent(request)) {
        // Funzioni delle librerie Apache per l'upload
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        items = upload.parseRequest(request);
        ////from  ww w  .ja v  a2 s  . c  o m
        for (FileItem item : items) {
            String name = item.getFieldName();
            //le form che prevedono l'upload di un file devono avere il campo del file chiamato in questo modo
            if (name.startsWith("file_to_upload")) {
                files.put(name, item);
            } else {
                info.put(name, item.getString());
            }
        }
        info.put("files", files);
        return info;
    }
    return null;
}

From source file:com.yeoou.fckeditor.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*  w w  w .  ja 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.
 */
@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 {
                upload.setHeaderEncoding("UTF-8");
                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);

                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                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.wabacus.WabacusFacade.java

public static void uploadFile(HttpServletRequest request, HttpServletResponse response) {
    PrintWriter out = null;//from   w w w.ja  va  2 s  .  c  om
    try {
        out = response.getWriter();
    } catch (IOException e1) {
        throw new WabacusRuntimeException("response?PrintWriter", e1);
    }
    out.println(
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
    out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + Config.encode + "\">");
    importWebresources(out);
    if (Config.getInstance().getSystemConfigValue("prompt-dialog-type", "artdialog").equals("artdialog")) {
        out.print("<script type=\"text/javascript\"  src=\"" + Config.webroot
                + "webresources/component/artDialog/artDialog.js\"></script>");
        out.print("<script type=\"text/javascript\"  src=\"" + Config.webroot
                + "webresources/component/artDialog/plugins/iframeTools.js\"></script>");
    }
    /**if(true)
    {
    out.print("<table style=\"margin:0px;\"><tr><td style='font-size:13px;'><font color='#ff0000'>");
    out.print("???WabacusDemo????\n\rWabacusDemo.war?samples/");
    out.print("</font></td></tr></table>");
    return;
    }*/
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    String repositoryPath = FilePathAssistant.getInstance().standardFilePath(Config.webroot_abspath
            + File.separator + "wxtmpfiles" + File.separator + "upload" + File.separator);
    FilePathAssistant.getInstance().checkAndCreateDirIfNotExist(repositoryPath);
    factory.setRepository(new File(repositoryPath));
    ServletFileUpload fileUploadObj = new ServletFileUpload();
    fileUploadObj.setFileItemFactory(factory);
    fileUploadObj.setHeaderEncoding(Config.encode);
    List lstFieldItems = null;
    String errorinfo = null;
    try {
        lstFieldItems = fileUploadObj.parseRequest(request);
        if (lstFieldItems == null || lstFieldItems.size() == 0) {
            errorinfo = "??";
        }
    } catch (FileUploadException e) {
        log.error("?", e);
        errorinfo = "?";
    }
    Map<String, String> mFormFieldValues = new HashMap<String, String>();
    Iterator itFieldItems = lstFieldItems.iterator();
    FileItem item;
    while (itFieldItems.hasNext()) {//??mFormFieldValues??
        item = (FileItem) itFieldItems.next();
        if (item.isFormField()) {
            try {
                mFormFieldValues.put(item.getFieldName(), item.getString(Config.encode));
                request.setAttribute(item.getFieldName(), item.getString(Config.encode));
            } catch (UnsupportedEncodingException e) {
                log.warn("??????" + Config.encode
                        + "?", e);
            }
        }
    }
    String fileuploadtype = mFormFieldValues.get("FILEUPLOADTYPE");
    AbsFileUpload fileUpload = getFileUploadObj(request, fileuploadtype);
    boolean isPromtAuto = true;
    if (fileUpload == null) {
        errorinfo = "";
    } else if (errorinfo == null || errorinfo.trim().equals("")) {
        fileUpload.setMFormFieldValues(mFormFieldValues);
        errorinfo = fileUpload.doFileUpload(lstFieldItems, out);
        if (fileUpload.getInterceptorObj() != null) {
            isPromtAuto = fileUpload.getInterceptorObj().beforeDisplayFileUploadPrompt(request, lstFieldItems,
                    fileUpload.getMFormFieldValues(), errorinfo, out);
        }
    }
    out.println("<script language='javascript'>");
    out.println("  try{hideLoadingMessage();}catch(e){}");
    out.println("</script>");
    if (isPromtAuto) {
        if (errorinfo == null || errorinfo.trim().equals("")) {
            out.println("<script language='javascript'>");
            fileUpload.promptSuccess(out, Config.getInstance()
                    .getSystemConfigValue("prompt-dialog-type", "artdialog").equals("artdialog"));
            out.println("</script>");
        } else {
            out.println("<table style=\"margin:0px;\"><tr><td style='font-size:13px;'><font color='#ff0000'>"
                    + errorinfo + "</font></td></tr></table>");
        }
    }
    if (errorinfo != null && !errorinfo.trim().equals("")) {
        if (fileUpload != null) {
            request.setAttribute("WX_FILE_UPLOAD_FIELDVALUES", fileUpload.getMFormFieldValues());
        }
        showUploadFilePage(request, out);
    } else if (!isPromtAuto) {//???????????
        out.println("<script language='javascript'>");
        if (Config.getInstance().getSystemConfigValue("prompt-dialog-type", "artdialog").equals("artdialog")) {
            out.println("art.dialog.close();");
        } else {
            out.println("parent.closePopupWin();");
        }
        out.println("</script>");
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.localepairs.LocalePairImportHandler.java

/**
 * Upload the properties file to FilterConfigurations/import folder
 * /*from   ww  w  .  j a v a  2s  .  c  o  m*/
 * @param request
 */
private File uploadFile(HttpServletRequest request) {
    File f = null;
    try {
        String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight"
                + File.separator + "LocalePairs" + 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:edu.wustl.bulkoperator.action.BulkHandler.java

/**
 * This method will be called to get request parameters.
 * @param request HttpServletRequest.//from  www  . ja  v  a 2 s.co  m
 * @param bulkOperationForm form.
 * @throws BulkOperationException Exception.
 */
private void getRequestParameters(HttpServletRequest request, BulkOperationForm bulkOperationForm)
        throws BulkOperationException {
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(new File(CommonServiceLocator.getInstance().getAppHome()));
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

        // If file size exceeds, a FileUploadException will be thrown
        servletFileUpload.setSizeMax(10000 * 1000 * 100 * 10);
        List<FileItem> fileItems;
        fileItems = servletFileUpload.parseRequest(request);
        Iterator<FileItem> itr = fileItems.iterator();
        while (itr.hasNext()) {
            FileItem fileItem = itr.next();
            //Check if not form field so as to only handle the file inputs
            //else condition handles the submit button input
            if (!fileItem.isFormField()) {
                if ("csvFile".equals(fileItem.getFieldName())) {
                    bulkOperationForm.setCsvFile(getFormFile(fileItem));
                } else {
                    bulkOperationForm.setXmlTemplateFile(getFormFile(fileItem));
                }
                logger.info("Field =" + fileItem.getFieldName());
            } else {
                if ("operation".equals(fileItem.getFieldName())) {
                    bulkOperationForm.setOperationName(fileItem.getString());
                }

            }
        }
    } catch (Exception exp) {
        ErrorKey errorkey = ErrorKey.getErrorKey("bulk.operation.request.param.error");
        throw new BulkOperationException(errorkey, exp, exp.getMessage());
    }
}

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);//from w  ww .j  av a  2 s .co  m

    //        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.insurance.manage.UploadFile.java

private void uploadFire(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    //       Create a factory for disk-based file items
    String custId = null;/*from www  .j a  v  a  2 s  . c  om*/
    String year = null;
    String license = null;
    CustomerManager cManage = new CustomerManager();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    factory.setRepository(new File("temp"));

    //       Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    HttpSession session = request.getSession();

    //       Parse the request
    //      System.out.println("--------- Uploading --------------");
    try {
        List /* FileItem */ items = upload.parseRequest(request);
        //          Process the uploaded items
        Iterator iter = items.iterator();
        File fi = null;
        File file = null;
        //         Calendar calendar = Calendar.getInstance();
        //          DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        //          String fileName = df.format(calendar.getTime()) + ".jpg";
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                //                System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType());
                if (item.getFieldName().equals("custId") && !item.getString().equals("")) {
                    custId = item.getString();
                    System.out.println("custId : " + custId);
                }
                if (item.getFieldName().equals("year") && !item.getString().equals("")) {
                    year = item.getString();
                    System.out.println("year : " + year);
                }
            } else {
                //                Handle Uploaded files.
                //                System.out.println("Handle Uploaded files.");
                String fileName = year + custId + ".jpg";
                if (item.getFieldName().equals("fire") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(getServletContext().getRealPath("/images/fire/" + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "firepic", fileName);
                }
            }
        }
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId);
    request.setAttribute("msg", "!!!Uploading !!!");
    getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response);

}

From source file:com.insurance.manage.UploadFile.java

private void uploadLife(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    //       Create a factory for disk-based file items
    String custId = null;// ww w .j  ava 2 s  .  c o m
    String year = null;
    String license = null;
    CustomerManager cManage = new CustomerManager();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    factory.setRepository(new File("temp"));

    //       Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    HttpSession session = request.getSession();

    //       Parse the request
    //      System.out.println("--------- Uploading --------------");
    try {
        List /* FileItem */ items = upload.parseRequest(request);
        //          Process the uploaded items
        Iterator iter = items.iterator();
        File fi = null;
        File file = null;
        //         Calendar calendar = Calendar.getInstance();
        //          DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        //          String fileName = df.format(calendar.getTime()) + ".jpg";
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                //                System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType());
                if (item.getFieldName().equals("custId") && !item.getString().equals("")) {
                    custId = item.getString();
                    System.out.println("custId : " + custId);
                }
                if (item.getFieldName().equals("year") && !item.getString().equals("")) {
                    year = item.getString();
                    System.out.println("year : " + year);
                }
            } else {
                //                Handle Uploaded files.
                //                System.out.println("Handle Uploaded files.");
                String fileName = year + custId + ".jpg";
                if (item.getFieldName().equals("life") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(getServletContext().getRealPath("/images/life/" + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "lifepic", fileName);
                }
            }
        }
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId);
    request.setAttribute("msg", "!!!Uploading !!!");
    getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response);

}