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

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

Introduction

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

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:com.shyshlav.functions.filework.download_image.java

public String download(HttpServletRequest request, HttpServletResponse response) throws IOException {
    request.setCharacterEncoding("UTF-8"); //  
    response.setCharacterEncoding("UTF-8");
    filePath = request.getSession().getServletContext().getInitParameter("avathars");
    System.out.println(filePath);
    isMultipart = ServletFileUpload.isMultipartContent(request);
    System.out.println(isMultipart);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    if (!isMultipart) {
        return "  ";
    }/* ww  w.  ja v  a 2 s .c om*/
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\test"));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    try {
        // Parse the request to get file items.
        List<FileItem> fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        //String name,String password,String email,String surname,String link_to_image,String about_me,String id
        String name = null;
        String password = null;
        String re_password = null;
        String surname = null;
        String about_me = null;
        String id = null;
        String link_to_server = null;
        String email = null;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (fi.isFormField()) {
                String fieldname = fi.getFieldName();
                String fieldvalue = fi.getString();
                if (fieldname.equals("name")) {
                    name = fi.getString("UTF-8");
                } else if (fieldname.equals("surname")) {
                    surname = fi.getString("UTF-8");
                } else if (fieldname.equals("password")) {
                    password = fi.getString("UTF-8");
                } else if (fieldname.equals("re_password")) {
                    re_password = fi.getString("UTF-8");
                } else if (fieldname.equals("about_me")) {
                    about_me = fi.getString("UTF-8");
                } else if (fieldname.equals("id")) {
                    id = fi.getString("UTF-8");
                } else if (fieldname.equals("email")) {
                    email = fi.getString("UTF-8");
                }
                System.out.println(fieldname + fieldvalue);
                if (fieldname == null || fieldvalue == null) {
                    return "? ? ? ";
                }
            }
            if (!fi.isFormField()) {
                if (!password.equals(re_password)) {
                    System.out.println(password + " - " + re_password);
                    return "  ?";
                }
                // Get the uploaded file parameters
                String fileName = email + ".png";
                link_to_server = "/musicbox/avathars/" + email + ".png".trim();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                System.out.println("Uploaded Filename: " + filePath + fileName);
            }
        }
        System.out.println(link_to_server);
        updateUser um = new updateUser();
        um.updateUser(name, password, surname, link_to_server, about_me, id);
    } catch (Exception ex) {
        System.out.println(ex);
        return "    1 ";
    }
    return "ok";
}

From source file:com.skin.taurus.http.servlet.UploadServlet.java

public void upload(HttpRequest request, HttpResponse response) throws IOException {
    int maxFileSize = 1024 * 1024;
    String repository = System.getProperty("java.io.tmpdir");
    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setRepository(new File(repository));
    factory.setSizeThreshold(maxFileSize * 2);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

    servletFileUpload.setFileSizeMax(maxFileSize);
    servletFileUpload.setSizeMax(maxFileSize);

    try {// w w w.ja  v a2  s  .  c  om
        HttpServletRequest httpRequest = new HttpServletRequestAdapter(request);
        List<?> list = servletFileUpload.parseRequest(httpRequest);

        for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
            FileItem item = (FileItem) iterator.next();

            if (item.isFormField()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Form Field: " + item.getFieldName() + " " + item.toString());
                }
            } else if (!item.isFormField()) {
                if (item.getFieldName() != null) {
                    String fileName = this.getFileName(item.getName());
                    String extension = this.getFileExtensionName(fileName);

                    if (this.isAllowed(extension)) {
                        try {
                            this.save(item);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    item.delete();
                } else {
                    item.delete();
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
}

From source file:controlador.SerCiudadano.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww  w.  j av a  2 s.c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    //Procesando el archivo .sql con los datos del cnr
    //en esta ruta se guarda temporalmente el archivo .sql
    Bitacora b = new Bitacora();
    String ruta = getServletContext().getRealPath("/") + "pages/procesos/";
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(40960);
        File repositoryPath = new File("/temp");
        diskFileItemFactory.setRepository(repositoryPath);
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        servletFileUpload.setSizeMax(81920); // bytes
        upload.setSizeMax(307200); // 1024 x 300 = 307200 bytes = 300 Kb
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                //este es el archivo que se envia en el campo file
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String tipo = item.getContentType();
                        long tamanio = item.getSize();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(ruta, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            String script = ruta + "" + nombre;
                            //consulta para importar registros
                            if (ConsultasDTO.ejecutar(
                                    "copy padronelectoral from '" + script + "' with (delimiter ',')")) {
                                out.print("Registros importados correctamente");
                            } else {
                                out.print("Hubo un error");
                            }

                        } else {
                            out.println("FALLO AL GUARDAR. NO EXISTE " + archivo.getAbsolutePath() + "</p>");
                        }
                    }
                } else {
                    //ac recogemos los duis de los magistrados
                    if (item.getFieldName().equals("dui1")) {
                        b.setMagistrado1(item.getString());
                    }
                    if (item.getFieldName().equals("dui2")) {
                        b.setMagistrado2(item.getString());
                    }
                    if (item.getFieldName().equals("dui3")) {
                        b.setMagistrado3(item.getString());
                    }

                }
            }
            //registramos en la base de datos los duis de los magistrados
            //que autorizaron la insercion de datos CNR
            b.setAccion("Registro de datos CNR");
            if (BitacoraDTO.agregarBitacora(b)) {
                out.print("<br>Bitacora agregada");
            } else {
                out.print("<br>Hubo un error al agregar la bitacora");
            }

        } catch (FileUploadException e) {
            out.println("Error Upload: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            out.println("Error otros: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:com.googlecode.psiprobe.controllers.deploy.UploadWarController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {

        File tmpWar = null;/*ww w  .  jav  a2 s  . c o  m*/
        String contextName = null;
        boolean update = false;
        boolean compile = false;
        boolean discard = false;

        //
        // parse multipart request and extract the file
        //
        FileItemFactory factory = new DiskFileItemFactory(1048000,
                new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);
        upload.setHeaderEncoding("UTF8");
        try {
            for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) {
                FileItem fi = (FileItem) it.next();
                if (!fi.isFormField()) {
                    if (fi.getName() != null && fi.getName().length() > 0) {
                        tmpWar = new File(System.getProperty("java.io.tmpdir"),
                                FilenameUtils.getName(fi.getName()));
                        fi.write(tmpWar);
                    }
                } else if ("context".equals(fi.getFieldName())) {
                    contextName = fi.getString();
                } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    update = true;
                } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    compile = true;
                } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    discard = true;
                }
            }
        } catch (Exception e) {
            logger.fatal("Could not process file upload", e);
            request.setAttribute("errorMessage", getMessageSourceAccessor()
                    .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() }));
            if (tmpWar != null && tmpWar.exists()) {
                tmpWar.delete();
            }
            tmpWar = null;
        }

        String errMsg = null;

        if (tmpWar != null) {
            try {
                if (tmpWar.getName().endsWith(".war")) {

                    if (contextName == null || contextName.length() == 0) {
                        String warFileName = tmpWar.getName().replaceAll("\\.war$", "");
                        contextName = "/" + warFileName;
                    }

                    contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName);

                    //
                    // pass the name of the newly deployed context to the presentation layer
                    // using this name the presentation layer can render a url to view compilation details
                    //
                    String visibleContextName = "".equals(contextName) ? "/" : contextName;
                    request.setAttribute("contextName", visibleContextName);

                    if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) {
                        logger.debug("updating " + contextName + ": removing the old copy");
                        getContainerWrapper().getTomcatContainer().remove(contextName);
                    }

                    if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) {
                        //
                        // move the .war to tomcat application base dir
                        //
                        String destWarFilename = getContainerWrapper().getTomcatContainer()
                                .formatContextFilename(contextName);
                        File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(),
                                destWarFilename + ".war");

                        FileUtils.moveFile(tmpWar, destWar);

                        //
                        // let Tomcat know that the file is there
                        //
                        getContainerWrapper().getTomcatContainer().installWar(contextName,
                                new URL("jar:" + destWar.toURI().toURL().toString() + "!/"));

                        Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName);
                        if (ctx == null) {
                            errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled",
                                    new Object[] { visibleContextName });
                        } else {
                            request.setAttribute("success", Boolean.TRUE);
                            if (discard) {
                                getContainerWrapper().getTomcatContainer().discardWorkDir(ctx);
                            }
                            if (compile) {
                                Summary summary = new Summary();
                                summary.setName(ctx.getName());
                                getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true);
                                request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE,
                                        summary);
                                request.setAttribute("compileSuccess", Boolean.TRUE);
                            }
                        }

                    } else {
                        errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists",
                                new Object[] { visibleContextName });
                    }
                } else {
                    errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure");
                }
            } catch (Exception e) {
                errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure",
                        new Object[] { e.getMessage() });
                logger.error("Tomcat throw an exception when trying to deploy", e);
            } finally {
                if (errMsg != null) {
                    request.setAttribute("errorMessage", errMsg);
                }
                tmpWar.delete();
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:com.manning.cmis.theblend.servlets.AddServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response, Session session)
        throws ServletException, IOException, TheBlendException {

    // check for multipart content
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        // we expected content -> return to add page
        dispatch("add.jsp", "Add something new. The Blend.", request, response);
    }//from  w  w w . j  a  v  a2 s. co m

    Map<String, Object> properties = new HashMap<String, Object>();
    File uploadedFile = null;
    String parentId = null;
    String parentPath = null;
    ObjectId newId = null;

    // process the request
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(50 * 1024 * 1024);

        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);

        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

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

                if (PARAM_PARENT_ID.equalsIgnoreCase(name)) {
                    parentId = item.getString();
                } else if (PARAM_PARENT_PATH.equalsIgnoreCase(name)) {
                    parentPath = item.getString();
                } else if (PARAM_TYPE_ID.equalsIgnoreCase(name)) {
                    properties.put(PropertyIds.OBJECT_TYPE_ID, item.getString());
                }
            } else {
                String name = item.getName();
                if (name == null) {
                    name = "file";
                } else {
                    // if the browser provided a path instead of a file name,
                    // strip off the path
                    int x = name.lastIndexOf('/');
                    if (x > -1) {
                        name = name.substring(x + 1);
                    }
                    x = name.lastIndexOf('\\');
                    if (x > -1) {
                        name = name.substring(x + 1);
                    }

                    name = name.trim();
                    if (name.length() == 0) {
                        name = "file";
                    }
                }

                properties.put(PropertyIds.NAME, name);

                uploadedFile = File.createTempFile("blend", "tmp");
                item.write(uploadedFile);
            }
        }
    } catch (Exception e) {
        throw new TheBlendException("Upload failed: " + e, e);
    }

    if (uploadedFile == null) {
        throw new TheBlendException("No content!");
    }

    try {
        // prepare the content stream
        ContentStream contentStream = null;
        try {
            String objectTypeId = (String) properties.get(PropertyIds.OBJECT_TYPE_ID);
            contentStream = prepareContentStream(session, uploadedFile, objectTypeId, properties);
        } catch (Exception e) {
            throw new TheBlendException("Upload failed: " + e, e);
        }

        // find the parent folder
        // (we don't deal with unfiled documents here)
        Folder parent = null;
        if (parentId != null) {
            parent = CMISHelper.getFolder(session, parentId, CMISHelper.LIGHT_OPERATION_CONTEXT,
                    "parent folder");
        } else {
            parent = CMISHelper.getFolderByPath(session, parentPath, CMISHelper.LIGHT_OPERATION_CONTEXT,
                    "parent folder");
        }

        // create the document
        try {
            newId = session.createDocument(properties, parent, contentStream, null);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Could not create document: " + cbe.getMessage(), cbe);
        } finally {
            try {
                contentStream.getStream().close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    } finally {
        // delete temp file
        uploadedFile.delete();
    }

    // show the newly created document
    redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response);
}

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

@Override
public WorkflowRequestParameter create(final HttpServletRequest request) throws FileUploadException {
    try {//from ww w. j a  va 2s  .co  m
        request.setCharacterEncoding(characterEncodingName);
    } catch (final UnsupportedEncodingException e) {
    }
    if (ServletFileUpload.isMultipartContent(request)) {
        final DiskFileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        factory.setSizeThreshold(1024);
        upload.setSizeMax(-1);
        upload.setHeaderEncoding(characterEncodingName);
        return new RequestMultipart(characterEncoding, upload, request);
    }
    return new RequestUrlencoded(request);
}

From source file:gsn.http.FieldUpload.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String msg;/* ww w . jav a  2  s .  co  m*/
    Integer code;
    PrintWriter out = res.getWriter();
    ArrayList<String> paramNames = new ArrayList<String>();
    ArrayList<String> paramValues = new ArrayList<String>();

    //Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        out.write("not multipart!");
        code = 666;
        msg = "Error post data is not multipart!";
        logger.error(msg);
    } else {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

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

        // Set overall request size constraint
        upload.setSizeMax(5 * 1024 * 1024);

        List items;
        try {
            // Parse the request
            items = upload.parseRequest(req);

            //building xml data out of the input
            String cmd = "";
            String vsname = "";
            Base64 b64 = new Base64();
            StringBuilder sb = new StringBuilder("<input>\n");
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.getFieldName().equals("vsname")) {
                    //define which cmd block is sent
                    sb.append("<vsname>" + item.getString() + "</vsname>\n");
                    vsname = item.getString();
                } else if (item.getFieldName().equals("cmd")) {
                    //define which cmd block is sent
                    cmd = item.getString();
                    sb.append("<command>" + item.getString() + "</command>\n");
                    sb.append("<fields>\n");
                } else if (item.getFieldName().split(";")[0].equals(cmd)) {
                    //only for the defined cmd       
                    sb.append("<field>\n");
                    sb.append("<name>" + item.getFieldName().split(";")[1] + "</name>\n");
                    paramNames.add(item.getFieldName().split(";")[1]);
                    if (item.isFormField()) {
                        sb.append("<value>" + item.getString() + "</value>\n");
                        paramValues.add(item.getString());
                    } else {
                        sb.append("<value>" + new String(b64.encode(item.get())) + "</value>\n");
                        paramValues.add(new String(b64.encode(item.get())));
                    }
                    sb.append("</field>\n");
                }
            }
            sb.append("</fields>\n");
            sb.append("</input>\n");

            //do something with xml aka statement.toString()

            AbstractVirtualSensor vs = null;
            try {
                vs = Mappings.getVSensorInstanceByVSName(vsname).borrowVS();
                vs.dataFromWeb(cmd, paramNames.toArray(new String[] {}),
                        paramValues.toArray(new Serializable[] {}));
            } catch (VirtualSensorInitializationFailedException e) {
                logger.warn("Sending data back to the source virtual sensor failed !: " + e.getMessage(), e);
            } finally {
                Mappings.getVSensorInstanceByVSName(vsname).returnVS(vs);
            }

            code = 200;
            msg = "The upload to the virtual sensor went successfully! (" + vsname + ")";
        } catch (ServletFileUpload.SizeLimitExceededException e) {
            code = 600;
            msg = "Upload size exceeds maximum limit!";
            logger.error(msg, e);
        } catch (Exception e) {
            code = 500;
            msg = "Internal Error: " + e;
            logger.error(msg, e);
        }

    }
    //callback to the javascript
    out.write("<script>window.parent.GSN.msgcallback('" + msg + "'," + code + ");</script>");
}

From source file:edu.gmu.csiss.automation.pacs.servlet.FileUploadServlet.java

/**
 * Processes requests for both HTTP//www.ja  v  a 2s  .  c o  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    res.setContentType("text/plain;charset=gbk");

    res.setContentType("text/html; charset=utf-8");
    PrintWriter pw = res.getWriter();
    try {
        //initialize the prefix url
        if (prefix_url == null) {
            //                String hostname = req.getServerName ();
            //                int port = req.getServerPort ();
            //                prefix_url = "http://"+hostname+":"+port+"/igfds/"+relativePath+"/";
            //updated by Ziheng - on 8/27/2015
            //This method should be used everywhere.
            int num = req.getRequestURI().indexOf("/PACS");
            String prefix = req.getRequestURI().substring(0, num + "/PACS".length()); //in case there is something before PACS
            prefix_url = req.getScheme() + "://" + req.getServerName()
                    + ("http".equals(req.getScheme()) && req.getServerPort() == 80
                            || "https".equals(req.getScheme()) && req.getServerPort() == 443 ? ""
                                    : ":" + req.getServerPort())
                    + prefix + "/" + relativePath + "/";
        }
        pw.println("<!DOCTYPE html>");
        pw.println("<html>");
        String head = "<head>" + "<title>File Uploading Response</title>"
                + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
                + "<script type=\"text/javascript\" src=\"js/TaskGridTool.js\"></script>" + "</head>";
        pw.println(head);
        pw.println("<body>");

        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold  2M 
        //extend to 2M - updated by ziheng - 9/25/2014
        diskFactory.setSizeThreshold(2 * 1024);
        // repository 
        diskFactory.setRepository(new File(tempPath));

        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        // 2M
        upload.setSizeMax(2 * 1024 * 1024);
        // HTTP
        List fileItems = upload.parseRequest(req);
        Iterator iter = fileItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                processFormField(item, pw);
            } else {
                processUploadFile(item, pw);
            }
        } // end while()
          //add some buttons for further process
        pw.println("<input type=\"button\" id=\"bt\" value=\"load\" onclick=\"load();\">");
        pw.println("<input type=\"button\" id=\"close\" value=\"close window\" onclick=\"window.close();\">");
        pw.println("</body>");
        pw.println("</html>");
    } catch (Exception e) {
        e.printStackTrace();
        pw.println("ERR:" + e.getClass().getName() + ":" + e.getLocalizedMessage());
    } finally {
        pw.flush();
        pw.close();
    }
}

From source file:UploadDownloadFile.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);/*w  w  w . ja v a2  s.  co m*/
    String filePath;
    final String clientip = request.getRemoteAddr().replace(":", "_");
    filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/"
            + clientip + "/";
    System.out.println("filePath = " + filePath);
    // filePath = "/Users/jhovarie/Desktop/webuploaded/";
    File f = new File(filePath);
    if (!f.exists()) {
        f.mkdirs();
    }

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    //factory.setRepository(new File("c:\\temp"));
    factory.setRepository(new File(filePath));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<a href='" + currenthost + "/UploadDownloadFile/index.html'><< BACK <<</a><br/>");
        String fileName = "";
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }

        out.println("Target Location = " + filePath);
        out.write(
                "<br/><a href=\"UploadDownloadFile?fileName=" + fileName + "\">Download " + fileName + "</a>");
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println("Error in Process " + ex);
    }
}

From source file:business.controllers.UploadImageController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();/*  ww  w. j  a  v  a2 s . c o  m*/
        return;
    }
    String oauthCode = "";
    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE);
    upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE);
    List formItems = new ArrayList();
    try {
        // parses the request's content to extract file data
        formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();
        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (item.getFieldName().equals("oauthcode")) {
                oauthCode = item.getString();
            }

        }

    } catch (FileUploadException ex) {
        logger.error("Write image:" + ex);
    }

    //checkLogin
    BusinessChatHandler handler = new BusinessChatHandler();
    try {
        if (handler.isLogin(oauthCode)) {
            uploadImage(request, response, formItems);
        }
    } catch (TException ex) {
        java.util.logging.Logger.getLogger(UploadImageController.class.getName()).log(Level.SEVERE, null, ex);
    }
}