Example usage for org.apache.commons.fileupload DiskFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload DiskFileUpload setSizeMax

Introduction

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

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:com.krawler.esp.portalmsg.forummsgcomm.java

public static void doPost(Connection conn, java.util.List fileItems, String postid,
        java.sql.Timestamp docdatemod, String userid, String sendefolderpostid) throws ServiceException {
    try {/*from www.  ja  v a2  s.c o m*/
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "attachment";
        java.io.File destDir = new java.io.File(destinationDirectory);
        String Ext = "";
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        String fileid;
        long size;
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        for (java.util.Iterator i = fileItems.iterator(); i.hasNext();) {
            org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) i.next();
            if (!fi.isFormField()) {
                String fileName = null;
                fileid = UUID.randomUUID().toString();
                try {
                    fileName = getFileName(fi);
                    //                        fileName = new String(fi.getName().getBytes(), "UTF8");
                    if (fileName.contains(".")) {
                        Ext = fileName.substring(fileName.lastIndexOf("."));
                    }
                    size = fi.getSize();
                    if (size != 0) {

                        File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                        fi.write(uploadFile);
                        fildoc(conn, fileid, fileName, docdatemod, postid, fileid + Ext, userid, size,
                                sendefolderpostid);
                    }

                } catch (Exception e) {
                    throw ServiceException.FAILURE("ProfileHandler.updateProfile", e);
                }
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(forummsgcomm.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.krawler.esp.portalmsg.Forum.java

public static String insertForumPost(Connection conn, HttpServletRequest request)
        throws ServiceException, ParseException, JSONException {
    org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
    java.util.List fileItems = null;
    org.apache.commons.fileupload.FileItem fi = null;
    int sizeinmb = forummsgcomm.getmaxfilesize(conn, AuthHandler.getCompanyid(request, false));
    long maxsize = sizeinmb * 1024 * 1024;
    boolean fileupload = false;
    fu.setSizeMax(maxsize);
    java.util.HashMap arrParam = new java.util.HashMap();
    JSONObject jobj = new JSONObject();
    try {/*from   w  w w  .  j  a  v a2 s.c om*/
        fileItems = fu.parseRequest(request);
    } catch (org.apache.commons.fileupload.FileUploadException e) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jerrtemp.put("msg", "Problem while uploading file.");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
        fi = (org.apache.commons.fileupload.FileItem) k.next();
        arrParam.put(fi.getFieldName(), fi.getString());
        if (!fi.isFormField()) {
            if (fi.getSize() > maxsize) {
                com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
                jerrtemp.put("Success", "Fail");
                jerrtemp.put("msg", "For attachments, maximum file size allowed is " + sizeinmb + " MB");
                jobj.append("data", jerrtemp);
                return jobj.toString();
            }
            fileupload = true;
        }
    }
    //                destinationDirectory = com.krawler.esp.handlers.StorageHandler
    //               .GetDocStorePath()
    int firstReply = Integer.parseInt(request.getParameter("firstReply"));
    String ptext = java.net.URLDecoder.decode(arrParam.get("ptxt").toString());
    String repto = request.getParameter("repto");
    String title = java.net.URLDecoder.decode(arrParam.get("title").toString());
    String u_id = request.getParameter("userId");
    String group_id = request.getParameter("groupId");
    DbResults rs = null;
    DbResults rs1 = null;
    DbResults rs2 = null;
    String post_id = UUID.randomUUID().toString();
    String topic_id = "1";
    String topic_title = null;
    String dateTime = null;
    String UserName = null;
    String Image = null;
    String query = null;
    JSONStringer j = new JSONStringer();

    String temp = null;
    title = StringUtil.serverHTMLStripper(title);

    group_id = StringUtil.serverHTMLStripper(group_id);
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    java.util.Date d = new java.util.Date();
    java.sql.Timestamp sqlPostDate = new Timestamp(d.getTime());
    if (StringUtil.isNullOrEmpty(repto) /*|| StringUtil.isNullOrEmpty(title)*/ || StringUtil.isNullOrEmpty(u_id)
            || StringUtil.isNullOrEmpty(group_id)) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    if (fileupload) {
        forummsgcomm.doPost(conn, fileItems, post_id, sqlPostDate, u_id, "");
    }
    if (firstReply == 0) {

        query = "INSERT INTO krawlerforum_topics(topic_id, group_id, topic_title, topic_poster, post_time, post_subject,post_text, ifread,flag) VALUES (?, ?, ?, ?, ?, ?,?, ?, ?)";
        DbUtil.executeUpdate(conn, query,
                new Object[] { post_id, group_id, title, u_id, sqlPostDate, ptext, ptext, false, false });

        post_id = "topic" + post_id;
    } else if (firstReply == 1) {
        repto = repto.substring(5);

        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title,post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, repto, false, false, "-999" });

        repto = "topic" + repto;
    } else if (firstReply == 2) {
        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title, post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, "1", false, false, repto });

    }

    query = "SELECT userlogin.username,image FROM users inner join userlogin on users.userid = userlogin.userid where users.userid=?;";
    rs2 = DbUtil.executeQuery(conn, query, u_id);

    if (rs2.next()) {
        UserName = (rs2.getString(1));
        Image = (rs2.getString(2));
    }
    String userTime = Timezone.toCompanyTimezone(conn, sqlPostDate.toString(),
            CompanyHandler.getCompanyByUser(conn, u_id));
    java.util.Date tempdate = sdf.parse(userTime);
    com.krawler.utils.json.base.JSONObject jtemp = new com.krawler.utils.json.base.JSONObject();
    jtemp.put("Success", "Success");
    jtemp.put("ID", post_id);
    jtemp.put("Subject", title);
    jtemp.put("Received", sdf.format(tempdate));
    jtemp.put("From", UserName);
    jtemp.put("Details", "");
    jtemp.put("Flag", "false");
    jtemp.put("Image", Image);
    jtemp.put("Parent", repto);
    jobj.append("data", jtemp);
    /*temp = j.object().key("Success").value("Success").key("ID").value(
    post_id).key("Subject").value(title).key("Received").value(
    sdf1.format(tempdate).toString()).key("From").value(UserName)
    .key("Details").value("").key("Flag").value("false").key(
    "Image").value(Image).key("Parent").value(repto)
    .endObject().toString();*/
    return jobj.toString();
}

From source file:com.krawler.esp.servlets.importToDoTask.java

public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException {
    String result = "";
    try {//w  ww  . jav  a2  s  . c  o  m
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importplans";
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }

        long size = 0;
        String Ext = "";
        String fileName = null;
        boolean fileupload = false;
        java.io.File destDir = new java.io.File(destinationDirectory);
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        java.util.HashMap arrParam = new java.util.HashMap();
        for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
            fi = (org.apache.commons.fileupload.FileItem) k.next();
            arrParam.put(fi.getFieldName(), fi.getString());
            if (!fi.isFormField()) {
                size = fi.getSize();
                fileName = new String(fi.getName().getBytes(), "UTF8");

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
            }
            if (size != 0) {
                File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);
                result = fileid + Ext;
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    }
    return result;
}

From source file:com.w4t.engine.requests.FileUploadRequest.java

public FileUploadRequest(final HttpServletRequest request) throws ServletException {
    super(request);
    IConfiguration configuration = ConfigurationReader.getConfiguration();
    IFileUpload fileUpload = configuration.getFileUpload();
    UploadRequestFileItemFactory factory = new UploadRequestFileItemFactory();
    DiskFileUpload upload = new DiskFileUpload(factory);
    upload.setSizeThreshold(fileUpload.getMaxMemorySize());
    upload.setSizeMax(fileUpload.getMaxMemorySize());
    upload.setRepositoryPath(FileUploadRequest.SYSTEM_TEMP_DIR);
    try {//ww  w.  j a  v  a  2 s . co  m
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            parameters.put(item.getFieldName(), item);
        }

    } catch (FileUploadException e) {
        throw new ServletExceptionAdapter(e);
    }
}

From source file:info.magnolia.cms.filters.CommonsFileUploadMultipartRequestFilter.java

/**
 * Create a new <code>DiskFileUpload</code>.
 *///from w w  w  .  j  ava 2 s  . c o m
private DiskFileUpload newDiskFileUpload() {
    DiskFileUpload upload = new DiskFileUpload();
    upload.setSizeMax(this.maxFileSize);
    upload.setRepositoryPath(Path.getTempDirectoryPath());

    return upload;
}

From source file:forseti.JUploadFichero.java

@SuppressWarnings("rawtypes")
public boolean procesaFicheros(HttpServletRequest req, PrintWriter out) {
    try {//from  w w w  .j  a  va  2s . co m
        // construimos el objeto que es capaz de parsear la pericin
        DiskFileUpload fu = new DiskFileUpload();

        // maximo numero de bytes
        fu.setSizeMax(1024 * 512); // 512 K

        depura("Ponemos el tamao mximo");
        // tamao por encima del cual los ficheros son escritos directamente en disco
        fu.setSizeThreshold(4096);

        // directorio en el que se escribirn los ficheros con tamao superior al soportado en memoria
        fu.setRepositoryPath("/tmp");

        // ordenamos procesar los ficheros
        List fileItems = fu.parseRequest(req);

        if (fileItems == null) {
            depura("La lista es nula");
            return false;
        }

        // Iteramos por cada fichero

        Iterator i = fileItems.iterator();
        FileItem actual = null;
        depura("estamos en la iteracin");

        while ((actual = (FileItem) i.next()) != null) {
            String fileName = actual.getName();
            out.println("<br>Nos han subido el archivo: " + fileName);

            // construimos un objeto file para recuperar el trayecto completo
            File fichero = new File(fileName);
            depura("El nombre del fichero es " + fichero.getName());

            // nos quedamos solo con el nombre y descartamos el path
            fichero = new File("../tomcat/webapps/ROOT/forsetidoc/IMG/" + fichero.getName());

            // escribimos el fichero colgando del nuevo path
            actual.write(fichero);
        }

    } catch (Exception e) {
        if (e != null)
            depura("Error de Aplicacin " + e.getMessage());

        return false;
    }

    return true;
}

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

public void doPost(List fileItems, String filename, String destinationDirectory) {
    File destDir = new File(destinationDirectory);
    Ext = "";/*  ww  w . j av a  2 s .  c o  m*/
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setSizeThreshold(4096);
    fu.setRepositoryPath(destinationDirectory);
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
            String fileName = null;
            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                if (fileName.contains("."))
                    Ext = fileName.substring(fileName.lastIndexOf("."));
                if (fi.getSize() != 0) {
                    this.isUploaded = true;
                    File uploadFile = new File(destinationDirectory + "/" + filename + Ext);
                    fi.write(uploadFile);
                    imgResize(destinationDirectory + "/" + filename + Ext, 100, 100,
                            destinationDirectory + "/" + filename + "_100");
                    imgResize(destinationDirectory + "/" + filename + Ext, 35, 35,
                            destinationDirectory + "/" + filename);

                } else {
                    this.isUploaded = false;
                }
            } catch (Exception e) {
                logger.warn(e.getMessage(), e);
            }
        }
    }

}

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

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

From source file:com.fdt.sdl.admin.ui.action.UploadAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    if (!SecurityUtil.isAdminUser(request))
        return (mapping.findForward("welcome"));

    ActionMessages messages = new ActionMessages();
    ActionMessages errors = new ActionMessages();

    if (FileUpload.isMultipartContent(request)) {
        try {//w  w w  .ja va2s .  c o m
            //read old dataset values
            ServerConfiguration sc = ServerConfiguration.getServerConfiguration();
            ArrayList<DatasetConfiguration> old_dcs = ServerConfiguration.getDatasetConfigurations();
            Map<String, Long> oldModifiedTimes = new HashMap<String, Long>(old_dcs.size());
            for (DatasetConfiguration old_dc : old_dcs) {
                oldModifiedTimes.put(old_dc.getName(), old_dc.getConfigFile().lastModified());
            }

            DiskFileUpload upload = new DiskFileUpload();
            upload.setSizeMax(10 * 1024 * 1024);
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                } else {
                    String fileName = (new File(item.getName())).getName();
                    if (fileName.endsWith(".zip")) {
                        try {
                            extractZip(item.getInputStream());
                        } catch (Exception ee) {
                            logger.error("exception for zip:" + ee);
                            ee.printStackTrace();
                        }
                    }
                }
            }
            messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("action.uploadFiles.success"));
            saveMessages(request, messages);

            //merge old values into the new data set
            if (sc.getIsMergingOldDatasetValues()) {
                ArrayList<DatasetConfiguration> new_dcs = ServerConfiguration.getDatasetConfigurations();
                for (DatasetConfiguration new_dc : new_dcs) {
                    if (oldModifiedTimes.get(new_dc.getName()) != null
                            && new_dc.getConfigFile().lastModified() > oldModifiedTimes.get(new_dc.getName())) {
                        for (DatasetConfiguration old_dc : old_dcs) {
                            if (new_dc.getName() == old_dc.getName()) {
                                new_dc.merge(old_dc);
                                new_dc.save();
                                break;
                            }
                        }
                    }
                }
            }

            if (sc.getAllowedLicenseLevel() > 0) {
                //reload from the disk
                ArrayList<DatasetConfiguration> dcs = ServerConfiguration.getDatasetConfigurations();
                for (DatasetConfiguration dc : dcs) {
                    try {
                        SchedulerTool.scheduleIndexingJob(dc);
                    } catch (Throwable t) {
                        logger.info("Failed to schedule for " + dc.getName() + ": " + t.toString());
                    }
                }
            }

            return mapping.findForward("continue");
        } catch (Exception e) {
            errors.add("error", new ActionMessage("action.uploadFiles.error"));
            saveErrors(request, errors);
            return mapping.findForward("continue");
        }
    } else { // from other page
        //
    }

    return mapping.findForward("continue");
}

From source file:forseti.JSubirArchivo.java

@SuppressWarnings("rawtypes")
public int processFiles(HttpServletRequest request, boolean onlyOne) // Request No debe contener parametros de formulario, sino solo los parmetro del archivo
{
    int numFiles = 0, thisFile = 0;

    try {//from  ww  w  . j  a v  a2s .  com
        // construimos el objeto que es capaz de parsear la pericin
        DiskFileUpload fu = new DiskFileUpload();
        // maximo numero de bytes
        fu.setSizeMax(1024 * m_MaxSize); // 512 K
        // tamao por encima del cual los ficheros son escritos directamente en disco
        fu.setSizeThreshold(4096);
        // directorio en el que se escribirn los ficheros con tamao superior al soportado en memoria
        fu.setRepositoryPath("/tmp");
        // ordenamos procesar los ficheros
        List fileItems = fu.parseRequest(request);
        if (fileItems == null) {
            m_Error += JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " null";
            return 0;
        }
        // Iteramos por cada fichero
        Iterator i = fileItems.iterator();
        FileItem actual = null;

        if (onlyOne) {
            actual = (FileItem) i.next();
            String fileName = actual.getName();
            // construimos un objeto file para recuperar el trayecto completo
            File file = new File(fileName);

            // Verifica que el archivo sea de la extension esperada
            for (int f = 0; f < m_Files.size(); f++) {
                String ext = "." + getExt(f).toLowerCase();
                System.out.println("Archivo: " + fileName + " Ext esperada: " + ext);

                if (file.getName().toLowerCase().indexOf(ext) != -1) {
                    // nos quedamos solo con el nombre y descartamos el path
                    file = new File(m_Path + file.getName());
                    // escribimos el fichero colgando del nuevo path
                    actual.write(file);
                    MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile);
                    part.m_File = file.getName();

                    numFiles += 1;
                    break;
                }
            }

            if (numFiles == 0)
                m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName();

        } else {
            while ((actual = (FileItem) i.next()) != null) {
                String fileName = actual.getName();
                // construimos un objeto file para recuperar el trayecto completo
                File file = new File(fileName);
                String ext = "." + getExt(thisFile).toLowerCase();
                System.out.println("Archivo: " + fileName + " Ext esperada: " + ext);

                // Verifica que el archivo sea de la extension esperada
                if (file.getName().toLowerCase().indexOf(ext) != -1) {
                    // nos quedamos solo con el nombre y descartamos el path
                    file = new File(m_Path + file.getName());
                    // escribimos el fichero colgando del nuevo path
                    actual.write(file);
                    MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile);
                    part.m_File = file.getName();

                    numFiles += 1;
                } else
                    m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName() + " - "
                            + ext;

                thisFile += 1;
            }
            System.out.println("Despues while");
        }
    } catch (Exception e) {
        if (e != null)
            m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " " + e.getMessage(); //"Error al subir archivos: " + e.getMessage();
    }

    return numFiles;
}