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:msec.org.FileUploadServlet.java

static protected String FileUpload(Map<String, String> fields, List<String> filesOnServer,
        HttpServletRequest request, HttpServletResponse response) {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    //System.out.printf("temporary directory:%s", tmpDir);

    // Set factory constraints
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf8");

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

    // Parse the request
    try {/* w ww .ja v a  2s .c  o m*/
        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {//k -v

                String name = item.getFieldName();
                String value = item.getString("utf-8");
                fields.put(name, value);
            } else {

                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName == null || fileName.length() < 1) {
                    return "file name is empty.";
                }
                String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator
                        + fileName;
                //System.out.printf("upload file:%s", localFileName);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                File uploadedFile = new File(localFileName);
                item.write(uploadedFile);
                filesOnServer.add(localFileName);
            }

        }
        return "success";
    } catch (FileUploadException e) {
        e.printStackTrace();
        return e.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }

}

From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java

private static MultipartEntity getMultipartEntity(HttpServletRequest request) {
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Enumeration<String> en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String name = en.nextElement();
        String value = request.getParameter(name);
        try {//  w w  w  . j  a v a 2s .c o  m
            if (name.equals("file")) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(10000000);// 10 Mo
                List items = upload.parseRequest(request);
                Iterator itr = items.iterator();
                while (itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    File file = new File(item.getName());
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(item.get());
                    fos.flush();
                    fos.close();
                    entity.addPart(name, new FileBody(file, "application/zip"));
                }
            } else {
                entity.addPart(name, new StringBody(value.toString(), "text/plain", Charset.forName("UTF-8")));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (FileUploadException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (FileNotFoundException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }

    return entity;

}

From source file:Model.Picture.java

public static ArrayList<String> upload(HttpServletRequest request, int type) {
    ArrayList<String> errors = new ArrayList<String>();
    ArrayList<String> pictureNames = new ArrayList<String>();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(Constants.UPLOAD_SIZE_THRESHOLD);
    new File(Constants.TEMP_DIR).mkdirs();
    factory.setRepository(new File(Constants.TEMP_DIR));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(Constants.MAX_UPLOAD_SIZE);

    try {/*from   ww  w . j  a  va  2  s  . c  o m*/
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fileItem = (FileItem) i.next();
            String fileName = fileItem.getName();

            if (type == EXCEL_UPLOAD)
                errors.addAll(upload_excel(fileName, fileItem));
            else if (type == PICTURE_UPLOAD)
                errors.addAll(upload_picture(fileName, fileItem, pictureNames));
        }
    } catch (org.apache.commons.fileupload.FileUploadException e) {
        e.printStackTrace(System.out);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }

    if (type == PICTURE_UPLOAD)
        DataBaseTools.insertAndUpdateRecords(pictureNames);

    return errors;
}

From source file:jeeves.server.sources.ServiceRequestFactory.java

private static Element getMultipartParams(HttpServletRequest req, String uploadDir, int maxUploadSize)
        throws Exception {
    Element params = new Element("params");

    DiskFileItemFactory fif = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(fif);

    sfu.setSizeMax(((long) maxUploadSize) * 1024L * 1024L);

    try {/*  w w  w. java2 s.  c om*/
        for (Object i : sfu.parseRequest(req)) {
            FileItem item = (FileItem) i;
            String name = item.getFieldName();

            if (item.isFormField()) {
                String encoding = req.getCharacterEncoding();
                params.addContent(new Element(name).setText(item.getString(encoding)));
            } else {
                String file = item.getName();
                String type = item.getContentType();
                long size = item.getSize();

                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size);
                //--- remove path information from file (some browsers put it, like IE)

                file = simplifyName(file);
                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "File is called " + file + " after simplification");

                //--- we could get troubles if 2 users upload files with the same name
                item.write(new File(uploadDir, file));

                Element elem = new Element(name).setAttribute("type", "file")
                        .setAttribute("size", Long.toString(size)).setText(file);

                if (type != null)
                    elem.setAttribute("content-type", type);

                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem));
                params.addContent(elem);
            }
        }
    } catch (FileUploadBase.SizeLimitExceededException e) {
        throw new FileUploadTooBigEx();
    }

    return params;
}

From source file:edu.umd.cs.submitServer.MultipartRequest.java

public static MultipartRequest parseRequest(HttpServletRequest request, int maxSize, Logger logger,
        boolean strictChecking, ServletContext servletContext) throws IOException, ServletException {

    DiskFileItemFactory factory = getFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxSize);
    MultipartRequest multipartRequest = new MultipartRequest(logger, strictChecking);
    try {/*w  w  w.  ja  v  a 2  s .  com*/
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);

        for (FileItem item : items) {

            if (item.isFormField()) {
                multipartRequest.setParameter(item.getFieldName(), item.getString());
            } else {
                multipartRequest.addFileItem(item);
            }
        }
        return multipartRequest;
    } catch (FileUploadBase.SizeLimitExceededException e) {
        Debug.error("File upload is too big " + e.getActualSize() + " > " + e.getPermittedSize());
        Debug.error("upload info: " + multipartRequest);
        throw new ServletException(e);
    } catch (FileUploadException e) {
        Debug.error("FileUploadException: " + e);
        throw new ServletException(e);
    }
}

From source file:com.easyjf.web.core.FrameworkEngine.java

/**
 * ?requestform//  w ww  .  j a va  2 s.  c  o  m
 * 
 * @param request
 * @param formName
 * @return ??Form
 */
public static WebForm creatWebForm(HttpServletRequest request, String formName, Module module) {
    Map textElement = new HashMap();
    Map fileElement = new HashMap();
    String contentType = request.getContentType();
    String reMethod = request.getMethod();
    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))
            && (reMethod.equalsIgnoreCase("post"))) {
        //  multipart/form-data
        File file = new File(request.getSession().getServletContext().getRealPath("/temp"));
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(webConfig.getUploadSizeThreshold());
        factory.setRepository(file);
        ServletFileUpload sf = new ServletFileUpload(factory);
        sf.setSizeMax(webConfig.getMaxUploadFileSize());
        sf.setHeaderEncoding(request.getCharacterEncoding());
        List reqPars = null;
        try {
            reqPars = sf.parseRequest(request);
            for (int i = 0; i < reqPars.size(); i++) {
                FileItem it = (FileItem) reqPars.get(i);
                if (it.isFormField()) {
                    textElement.put(it.getFieldName(), it.getString(request.getCharacterEncoding()));// ??
                } else {
                    fileElement.put(it.getFieldName(), it);// ???
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
    } else if ((contentType != null) && contentType.equals("text/xml")) {
        StringBuffer buffer = new StringBuffer();
        try {
            String s = request.getReader().readLine();
            while (s != null) {
                buffer.append(s + "\n");
                s = request.getReader().readLine();
            }
        } catch (Exception e) {
            logger.error(e);
        }
        textElement.put("xml", buffer.toString());
    } else {
        textElement = request2map(request);
    }
    // logger.debug("????");
    WebForm wf = findForm(formName);
    wf.setValidate(module.isValidate());// ?validate?Form
    if (wf != null) {
        wf.setFileElement(fileElement);
        wf.setTextElement(textElement);
    }
    return wf;
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

public static ServletFileUpload getUploader(long maxSize) {
    DiskFileItemFactory dfif = new DiskFileItemFactory();
    dfif.setSizeThreshold(32 * 1024);//from   ww  w.j a  v a2 s .co m
    dfif.setRepository(new File(getUploadDir()));
    ServletFileUpload upload = new ServletFileUpload(dfif);
    upload.setSizeMax(maxSize);
    upload.setHeaderEncoding("utf-8");
    return upload;
}

From source file:kelly.core.argument.CommonsFileUploadActionArgumentResolver.java

@Override
public Object resolve(ActionArgument actionArgument, Castor castor) {
    Multipart annotation = actionArgument.getAnnotation(Multipart.class);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository("".equals(annotation.tempdir()) ? DEFAULT_TEMP_DIR : new File(annotation.tempdir()));
    factory.setSizeThreshold(annotation.sizeThreshold());

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(annotation.maxSize());

    try {//from w  w w.  jav  a2s . c  o m
        List<FileItem> items = upload.parseRequest(WebContextHolder.getInstance().getRequest());
        return items.toArray(new FileItem[items.size()]);
    } catch (FileUploadException e) {
        throw new kelly.core.exception.FileUploadException(e);
    }
}

From source file:com.adanac.module.blog.servlet.UploadImage.java

@Override
protected void service() throws ServletException, IOException {
    HttpServletRequest request = getRequest();
    String path = null;/*ww w.  ja v a2s.co m*/
    DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024,
            new File(Configuration.getContextPath("temp")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(3 * 1024 * 1024);
    try {
        List<FileItem> items = upload.parseRequest(request);
        FileItem fileItem = null;
        if (items != null && items.size() > 0 && StringUtils.isNotBlank((fileItem = items.get(0)).getName())) {
            String fileName = fileItem.getName();
            if (!fileName.endsWith(".jpg") && !fileName.endsWith(".gif") && !fileName.endsWith(".png")) {
                writeText("format_error");
                return;
            }
            path = ImageUtil.generatePath(fileItem.getName());
            IOUtil.copy(fileItem.getInputStream(), Configuration.getContextPath(path));
            fileItem.delete();
            writeText(Configuration.getSiteUrl(path));
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.picdrop.guice.provider.implementation.UploadHandlerProviderImpl.java

@Override
public ServletFileUpload get() throws IOException {
    ServletFileUpload handler = new ServletFileUpload(this.factoryProv.get());

    handler.setFileSizeMax(maxfilesize);
    handler.setSizeMax(maxrequestsize);

    return handler;
}