Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold.

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

From source file:de.ingrid.portal.portlets.ContactPortlet.java

public void processAction(ActionRequest request, ActionResponse actionResponse)
        throws PortletException, IOException {
    List<FileItem> items = null;
    File uploadFile = null;//from   ww  w .j a  v a2 s. c o m
    boolean uploadEnable = PortalConfig.getInstance().getBoolean(PortalConfig.PORTAL_CONTACT_UPLOAD_ENABLE,
            Boolean.FALSE);
    int uploadSize = PortalConfig.getInstance().getInt(PortalConfig.PORTAL_CONTACT_UPLOAD_SIZE, 10);

    RequestContext requestContext = (RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV);
    HttpServletRequest servletRequest = requestContext.getRequest();
    if (ServletFileUpload.isMultipartContent(servletRequest)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(uploadSize * 1000 * 1000);
        File file = new File(".");
        factory.setRepository(file);
        ServletFileUpload.isMultipartContent(servletRequest);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(uploadSize * 1000 * 1000);

        // Parse the request
        try {
            items = upload.parseRequest(servletRequest);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
        }
    }
    if (items != null) {
        // check form input
        if (request.getParameter(PARAMV_ACTION_DB_DO_REFRESH) != null) {

            ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY,
                    ContactForm.class);
            cf.populate(items);

            String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
            actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
            return;
        } else {
            Boolean isResponseCorrect = false;

            ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY,
                    ContactForm.class);
            cf.populate(items);
            if (!cf.validate()) {
                // add URL parameter indicating that portlet action was called
                // before render request

                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));

                return;
            }

            //remenber that we need an id to validate!
            String sessionId = request.getPortletSession().getId();
            //retrieve the response
            boolean enableCaptcha = PortalConfig.getInstance().getBoolean("portal.contact.enable.captcha",
                    Boolean.TRUE);

            if (enableCaptcha) {
                String response = request.getParameter("jcaptcha");
                for (FileItem item : items) {
                    if (item.getFieldName() != null) {
                        if (item.getFieldName().equals("jcaptcha")) {
                            response = item.getString();
                            break;
                        }
                    }
                }
                // Call the Service method
                try {
                    isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(sessionId,
                            response);
                } catch (CaptchaServiceException e) {
                    //should not happen, may be thrown if the id is not valid
                }
            }

            if (isResponseCorrect || !enableCaptcha) {
                try {
                    IngridResourceBundle messages = new IngridResourceBundle(
                            getPortletConfig().getResourceBundle(request.getLocale()), request.getLocale());

                    HashMap mailData = new HashMap();
                    mailData.put("user.name.given", cf.getInput(ContactForm.FIELD_FIRSTNAME));
                    mailData.put("user.name.family", cf.getInput(ContactForm.FIELD_LASTNAME));
                    mailData.put("user.employer", cf.getInput(ContactForm.FIELD_COMPANY));
                    mailData.put("user.business-info.telecom.telephone", cf.getInput(ContactForm.FIELD_PHONE));
                    mailData.put("user.business-info.online.email", cf.getInput(ContactForm.FIELD_EMAIL));
                    mailData.put("user.area.of.profession",
                            messages.getString("contact.report.email.area.of.profession."
                                    + cf.getInput(ContactForm.FIELD_ACTIVITY)));
                    mailData.put("user.interest.in.enviroment.info",
                            messages.getString("contact.report.email.interest.in.enviroment.info."
                                    + cf.getInput(ContactForm.FIELD_INTEREST)));
                    if (cf.hasInput(ContactForm.FIELD_NEWSLETTER)) {
                        Session session = HibernateUtil.currentSession();
                        Transaction tx = null;

                        try {

                            mailData.put("user.subscribed.to.newsletter", "yes");
                            // check for email address in newsletter list
                            tx = session.beginTransaction();
                            List newsletterDataList = session.createCriteria(IngridNewsletterData.class)
                                    .add(Restrictions.eq("emailAddress", cf.getInput(ContactForm.FIELD_EMAIL)))
                                    .list();
                            tx.commit();
                            // register for newsletter if not already registered
                            if (newsletterDataList.isEmpty()) {
                                IngridNewsletterData data = new IngridNewsletterData();
                                data.setFirstName(cf.getInput(ContactForm.FIELD_FIRSTNAME));
                                data.setLastName(cf.getInput(ContactForm.FIELD_LASTNAME));
                                data.setEmailAddress(cf.getInput(ContactForm.FIELD_EMAIL));
                                data.setDateCreated(new Date());

                                tx = session.beginTransaction();
                                session.save(data);
                                tx.commit();
                            }
                        } catch (Throwable t) {
                            if (tx != null) {
                                tx.rollback();
                            }
                            throw new PortletException(t.getMessage());
                        } finally {
                            HibernateUtil.closeSession();
                        }
                    } else {
                        mailData.put("user.subscribed.to.newsletter", "no");
                    }
                    mailData.put("message.body", cf.getInput(ContactForm.FIELD_MESSAGE));

                    Locale locale = request.getLocale();

                    String language = locale.getLanguage();
                    String localizedTemplatePath = EMAIL_TEMPLATE;
                    int period = localizedTemplatePath.lastIndexOf(".");
                    if (period > 0) {
                        String fixedTempl = localizedTemplatePath.substring(0, period) + "_" + language + "."
                                + localizedTemplatePath.substring(period + 1);
                        if (new File(getPortletContext().getRealPath(fixedTempl)).exists()) {
                            localizedTemplatePath = fixedTempl;
                        }
                    }

                    String emailSubject = messages.getString("contact.report.email.subject");

                    if (PortalConfig.getInstance().getBoolean("email.contact.subject.add.topic",
                            Boolean.FALSE)) {
                        if (cf.getInput(ContactForm.FIELD_ACTIVITY) != null
                                && !cf.getInput(ContactForm.FIELD_ACTIVITY).equals("none")) {
                            emailSubject = emailSubject + " - "
                                    + messages.getString("contact.report.email.area.of.profession."
                                            + cf.getInput(ContactForm.FIELD_ACTIVITY));
                        }
                    }

                    String from = cf.getInput(ContactForm.FIELD_EMAIL);
                    String to = PortalConfig.getInstance().getString(PortalConfig.EMAIL_CONTACT_FORM_RECEIVER,
                            "foo@bar.com");

                    String text = Utils.mergeTemplate(getPortletConfig(), mailData, "map",
                            localizedTemplatePath);
                    if (uploadEnable) {
                        if (uploadEnable) {
                            for (FileItem item : items) {
                                if (item.getFieldName() != null) {
                                    if (item.getFieldName().equals("upload")) {
                                        uploadFile = new File(sessionId + "_" + item.getName());
                                        // read this file into InputStream
                                        InputStream inputStream = item.getInputStream();

                                        // write the inputStream to a FileOutputStream
                                        OutputStream out = new FileOutputStream(uploadFile);
                                        int read = 0;
                                        byte[] bytes = new byte[1024];

                                        while ((read = inputStream.read(bytes)) != -1) {
                                            out.write(bytes, 0, read);
                                        }

                                        inputStream.close();
                                        out.flush();
                                        out.close();
                                        break;
                                    }
                                }
                            }
                        }
                        Utils.sendEmail(from, emailSubject, new String[] { to }, text, null, uploadFile);
                    } else {
                        Utils.sendEmail(from, emailSubject, new String[] { to }, text, null);
                    }
                } catch (Throwable t) {
                    cf.setError("", "Error sending mail from contact form.");
                    log.error("Error sending mail from contact form.", t);
                }

                // temporarily show same page with content
                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, PARAMV_ACTION_SUCCESS);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
            } else {
                cf.setErrorCaptcha();
                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
                return;
            }
        }
    } else {
        ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY, ContactForm.class);
        cf.setErrorUpload();
        String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
        actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
        return;
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

/**
 * Save the files to the docs directory.
 *///from  ww w  .  j a v  a 2  s .c  om
private Vector saveData(HttpServletRequest p_request, HttpSession p_session)
        throws EnvoyServletException, IOException {
    Vector outData = null;
    SessionManager sessionMgr = (SessionManager) p_session.getAttribute(SESSION_MANAGER);
    String jobName = (String) sessionMgr.getAttribute("jobName");
    String srcLocale = (String) sessionMgr.getAttribute("srcLocale");

    TimeZone tz = (TimeZone) p_session.getAttribute(WebAppConstants.USER_TIME_ZONE);
    long uploadDateInLong = System.currentTimeMillis();
    Date uploadDate = new Date(uploadDateInLong);
    String uploadPath = getUploadPath(jobName, srcLocale, uploadDate);
    try {
        boolean isMultiPart = ServletFileUpload.isMultipartContent(p_request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(p_request);

            List<String> files = null;
            for (int i = 0; i < items.size(); i++) {
                DiskFileItem item = (DiskFileItem) items.get(i);
                if (!item.isFormField()) {
                    StringBuffer sb = new StringBuffer();
                    sb.append(uploadPath);
                    sb.append(File.separator);
                    sb.append("GS_");
                    sb.append(System.currentTimeMillis());
                    sb.append(".zip");
                    String fileName = sb.toString();
                    File f = new File(fileName);
                    f.getParentFile().mkdirs();
                    item.write(f);
                    files = ZipIt.unpackZipPackage(fileName);

                    f.delete();
                    sessionMgr.setAttribute("numOfFiles", String.valueOf(files.size()));
                }
            }
            // now update the job name to include the timestamp
            String newJobName = uploadPath.substring(uploadPath.lastIndexOf(File.separator) + 1,
                    uploadPath.length());
            sessionMgr.setAttribute("jobName", newJobName);

            saveJobNote(sessionMgr, newJobName, uploadDateInLong);

            sendUploadCompletedEmail(files, sessionMgr, uploadDate, tz,
                    (Locale) p_session.getAttribute(WebAppConstants.UILOCALE));
        }

        return outData;
    } catch (Exception ex) {
        throw new EnvoyServletException(ex);
    }
}

From source file:com.ibm.btt.sample.SampleFileHandler.java

/**
 * Just handle one file upload in this handler, developer can extend to support 
 * multi-files upload //  w w  w.ja v a 2s.  c om
 */
@Override
public int saveFile(HttpServletRequest request) {
    int code = SAVE_FAILED;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //config the memory cache, if above the cache, the file data will be 
        // saved on cache folder 
        factory.setSizeThreshold(memCacheSize);
        // set up cache folder, when uploading, the tmp file 
        // will be saved in cache folder with a internal managed name. 
        factory.setRepository(new File(cachePath));

        ServletFileUpload upload = new ServletFileUpload(factory);
        // max size of a file 
        upload.setSizeMax(maxSize);

        try {
            if (isExpired()) {
                return REQ_TIMEOUT;
            }
            List<FileItem> fileItems = upload.parseRequest(request);
            // save file from request 
            code = uploadFilesFromReq(request, fileItems);
        } catch (SizeLimitExceededException e) {
            code = FILE_SIZE_EXCEED;
        } catch (FileUploadException e) {
            if (LOG.doDebug()) {
                LOG.debug("SampleFileHandler:saveFile() -- upload file stream was been cancelled", e);
            }
        }
    }
    return code;
}

From source file:com.intranet.intr.contabilidad.SupControllerFacturaCompra.java

@RequestMapping(value = "updateFacturaCompraRF.htm", method = RequestMethod.POST)
public String EupdateGastoRF_post(@ModelAttribute("ga") compraR ga, BindingResult result,
        HttpServletRequest request) {/*ww w  . ja va 2 s  .c o m*/
    String mensaje = "";
    String ruta = "redirect:Compra.htm";

    //MultipartFile multipart = c.getArchivo();
    System.out.println("olaEnviarMAILS");
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas";
    //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
    //String ubicacionArchivo="C:\\";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);

    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            if (gr.getIdcompra() != 0) {

                if (compraRService.existe(item.getName()) == false) {
                    System.out.println("updateeeNOMBRE FOTO: " + item.getName());
                    File file = new File(ubicacionArchivo, item.getName());
                    item.write(file);
                    gr.setNombreimg(item.getName());
                    compraRService.updateCompra(gr);
                }
            } else
                ruta = "redirect:Compra.htm";
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    return ruta;

}

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

public String execute(ActionInvocation invocation) throws Exception {

    Iterator iterator = parameters.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry mapEntry = (Map.Entry) iterator.next();
        System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue());
    }/*from  w w  w  . j a v  a2s.  com*/

    ActionContext ac = invocation.getInvocationContext();

    HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

    HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);
    /**
    * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org.
    *
    * Note:
    * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. 
    * 
    * 
    * 
    * 
    * 
    * 
    */

    // Directory to store all the uploaded files
    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;
    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 = request.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 + ": " + request.getHeader(header));
    }
    System.out.println("[parseRequest.jsp]  ------------------------------ ");

    try {
        // Get URL Parameters.
        Enumeration paraNames = request.getParameterNames();
        System.out.println("[parseRequest.jsp]  ------------------------------ ");
        System.out.println("[parseRequest.jsp]  Parameters: ");
        String pname;
        String pvalue;
        while (paraNames.hasMoreElements()) {
            pname = (String) paraNames.nextElement();
            pvalue = request.getParameter(pname);
            System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue);
            if (pname.equals("jufinal")) {
                bLastChunk = pvalue.equals("1");
            } else if (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 = request.getInputStream();
            int c;
            while ((c = is.read()) >= 0) {
                out.write(c);
            } //while
            is.close();
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
        } else if (!request.getContentType().startsWith("multipart/form-data")) {
            System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is "
                    + request.getContentType());
        } else {
            List /* FileItem */ items = upload.parseRequest(request);
            // 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());
                    // write the file
                    fileItem.write(fout);

                    //////////////////////////////////////////////////////////////////////////////////////
                    //Chunk management: if it was the last chunk, let's recover the complete file
                    //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) {
                                //System.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");
            PrintWriter out = ServletActionContext.getResponse().getWriter();
            out.write("SUCCESS");
            //System.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.glaf.mail.web.rest.MailTaskResource.java

@POST
@Path("/uploadMails")
@ResponseBody//from w  w w .j  a  va 2  s. c om
public void uploadMails(@Context HttpServletRequest request, @Context UriInfo uriInfo) {
    Map<String, Object> params = RequestUtils.getParameterMap(request);
    logger.debug(params);
    String taskId = request.getParameter("taskId");
    if (StringUtils.isEmpty(taskId)) {
        taskId = request.getParameter("id");
    }
    MailTask mailTask = null;
    if (StringUtils.isNotEmpty(taskId)) {
        mailTask = mailTaskService.getMailTask(taskId);
    }

    if (mailTask != null && StringUtils.equals(RequestUtils.getActorId(request), mailTask.getCreateBy())) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        // 
        factory.setRepository(new File(SystemProperties.getConfigRootPath() + "/temp/"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // ?
        // 
        // upload.setSizeMax(4194304);
        upload.setHeaderEncoding("UTF-8");
        List<?> fileItems = null;
        try {
            fileItems = upload.parseRequest(request);
            Iterator<?> i = fileItems.iterator();
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                logger.debug(fi.getName());
                if (fi.getName().endsWith(".txt")) {
                    byte[] bytes = fi.get();
                    String rowIds = new String(bytes);
                    List<String> addresses = StringTools.split(rowIds);
                    if (addresses.size() <= 100000) {
                        mailDataFacede.saveMails(taskId, addresses);
                        taskId = mailTask.getId();

                        if (mailTask.getLocked() == 0) {
                            QuartzUtils.stop(taskId);
                            QuartzUtils.restart(taskId);
                        } else {
                            QuartzUtils.stop(taskId);
                        }

                    } else {
                        throw new RuntimeException("mail addresses too many");
                    }
                    break;
                }
            }
        } catch (FileUploadException ex) {// ?
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
    }
}

From source file:com.aes.controller.EmpireController.java

@RequestMapping(value = "addpresentation", method = RequestMethod.POST)
public String doAction5(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute Chapter chapter, @ModelAttribute UserDetails loggedUser, BindingResult result,
        Map<String, Object> map) throws ServletException, IOException {
    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);
    Presentation tempPresentation = new Presentation();
    String chapterId = "";
    String description = "";
    try {//  w  w w  .  j a va2  s  .  c o m
        @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 = context.getRealPath("") + File.separator + "uploads" + File.separator
                            + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    tempPresentation.setFilePath(filePath);
                    tempPresentation.setFileSize(item.getSize());
                    tempPresentation.setFileType(item.getContentType());
                    tempPresentation.setFileName(fileName);
                } else {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if (name.equals("chapterId")) {
                        chapterId = value;
                    } else {
                        description = value;
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    tempPresentation.setRecordStatus(true);
    tempPresentation.setDescription(description);
    int id = Integer.parseInt(chapterId);
    tempPresentation.setChapter(this.service.getChapterById(id));
    service.addPresentation(tempPresentation);
    map.put("tempPresentation", new Presentation());
    map.put("chapterId", chapterId);
    map.put("presentations", service.getAllPresentationsByChapterId(Integer.parseInt(chapterId)));
    return "../../admin/add_presentation";
}

From source file:com.intranet.intr.contabilidad.EmpControllerFacturaCompra.java

@RequestMapping(value = "EaddFacturaCompraRF.htm", method = RequestMethod.POST)
public String addGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result,
        HttpServletRequest request) {// ww w .  ja  v  a2s.  co  m
    String mensaje = "";
    String ruta = "redirect:ECompra.htm";
    compraR gr = new compraR();
    //MultipartFile multipart = c.getArchivo();
    System.out.println("olaEnviarMAILS");
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas";
    //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
    //String ubicacionArchivo="C:\\";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);

    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            if (idPC != 0) {
                gr.setIdcompra(idPC);
                if (compraRService.existe(item.getName()) == false) {
                    System.out.println("NOMBRE FOTO: " + item.getName());
                    File file = new File(ubicacionArchivo, item.getName());
                    item.write(file);
                    gr.setNombreimg(item.getName());
                    compraRService.insertar(gr);
                }
            } else
                ruta = "redirect:ECompra.htm";
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    return ruta;

}

From source file:com.intranet.intr.contabilidad.EmpControllerFacturaCompra.java

@RequestMapping(value = "EupdateFacturaCompraRF.htm", method = RequestMethod.POST)
public String EupdateGastoRF_post(@ModelAttribute("ga") compraR ga, BindingResult result,
        HttpServletRequest request) {/*  w  w  w. j a  v  a  2s .  com*/
    String mensaje = "";
    String ruta = "redirect:ECompra.htm";

    //MultipartFile multipart = c.getArchivo();
    System.out.println("olaEnviarMAILS");
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas";
    //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
    //String ubicacionArchivo="C:\\";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);

    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            if (gr.getIdcompra() != 0) {

                if (compraRService.existe(item.getName()) == false) {
                    System.out.println("updateeeNOMBRE FOTO: " + item.getName());
                    File file = new File(ubicacionArchivo, item.getName());
                    item.write(file);
                    gr.setNombreimg(item.getName());
                    compraRService.updateCompra(gr);
                }
            } else
                ruta = "redirect:ECompra.htm";
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    return ruta;

}

From source file:com.intranet.intr.proveedores.SupControllerGestion.java

@RequestMapping(value = "fotoProveedor.htm", method = RequestMethod.POST)
public String fotoProveedor_post(@ModelAttribute("proveedor") proveedores prov, BindingResult result,
        HttpServletRequest request) {/*from  w w w.j a  va2s.  c  o m*/
    String mensaje = "";
    //C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosPerfil\\proveedores
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosPerfil\\proveedores";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);

    ServletFileUpload upload = new ServletFileUpload(factory);

    System.out.println("uPDAT FOTO ID proveedor: " + prov.getId());
    try {
        System.out.println("1: " + prov.getId());
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            System.out.println("2" + item.getName());
            File file = new File(ubicacionArchivo, item.getName());
            System.out.println("3" + prov.getId());
            item.write(file);
            System.out.println("4" + idProv);
            prov.setNombreFoto(item.getName());
            proveedoresService.UpdateImagen(prov);
            System.out.println("5: " + prov.getId());
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    //return "redirect:uploadFile.htm";

    return "redirect:Gestion.htm";

}