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:com.google.caja.ancillary.servlet.UploadPage.java

static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Process the uploaded items
    List<ObjectConstructor> uploads = Lists.newArrayList();

    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        int maxUploadSizeBytes = 1 << 18;
        factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold
        factory.setRepository(new File("/dev/null")); // Do not store on disk
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxUploadSizeBytes);

        writeHeader(resp);//from w ww  .j  a  v  a 2 s  .c o m

        // Parse the request
        List<?> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            resp.getWriter().write(Nodes.encode(ex.getMessage()));
            return;
        }

        for (Object fileItemObj : items) {
            FileItem item = (FileItem) fileItemObj; // Written for pre-generic java.
            if (!item.isFormField()) { // Then is a file
                FilePosition unk = FilePosition.UNKNOWN;
                String ct = item.getContentType();
                uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                        StringLiteral.valueOf(unk, item.getString()), "ip",
                        StringLiteral.valueOf(unk, item.getName()), "it",
                        ct != null ? StringLiteral.valueOf(unk, ct) : null));
            }
        }
    } else if (req.getParameter("url") != null) {
        List<URI> toFetch = Lists.newArrayList();
        boolean failed = false;
        for (String value : req.getParameterValues("url")) {
            try {
                toFetch.add(new URI(value));
            } catch (URISyntaxException ex) {
                if (!failed) {
                    failed = true;
                    resp.setStatus(500);
                    resp.setContentType("text/html;charset=UTF-8");
                }
                resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage()));
            }
        }
        if (failed) {
            return;
        }
        writeHeader(resp);
        FilePosition unk = FilePosition.UNKNOWN;
        for (URI uri : toFetch) {
            try {
                Content c = UriFetcher.fetch(uri);
                if (c.isText()) {
                    uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                            StringLiteral.valueOf(unk, c.getText()), "ip",
                            StringLiteral.valueOf(unk, uri.toString()), "it",
                            StringLiteral.valueOf(unk, c.type.mimeType)));
                }
            } catch (IOException ex) {
                resp.getWriter()
                        .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage()));
            }
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Content not multipart");
        return;
    }

    Expression notifyParent = (Expression) QuasiBuilder.substV(
            "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads));
    StringBuilder jsBuf = new StringBuilder();
    RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true);
    notifyParent.render(rc);
    rc.getOut().noMoreTokens();

    HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null));

    Writer out = resp.getWriter();
    out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString())));
}

From source file:edu.isi.karma.util.FileUtil.java

static public File downloadFileFromHTTPRequest(HttpServletRequest request, String destinationDirString) {
    // Download the file to the upload file folder

    File destinationDir = new File(destinationDirString);
    logger.debug("File upload destination directory: " + destinationDir.getAbsolutePath());

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

    // Set the size threshold, above which content will be stored on disk.
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB

    //Set the temporary directory to store the uploaded files of size above threshold.
    fileItemFactory.setRepository(destinationDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

    File uploadedFile = null;/*from   w  w w  . j  av a  2 s .  c  o m*/
    try {
        // Parse the request
        @SuppressWarnings("rawtypes")
        List items = uploadHandler.parseRequest(request);
        @SuppressWarnings("rawtypes")
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // Ignore Form Fields.
            if (item.isFormField()) {
                // Do nothing
            } else {
                //Handle Uploaded files. Write file to the ultimate location.
                uploadedFile = new File(destinationDir, item.getName());
                if (item instanceof DiskFileItem) {
                    DiskFileItem t = (DiskFileItem) item;
                    if (!t.getStoreLocation().renameTo(uploadedFile))
                        item.write(uploadedFile);
                } else
                    item.write(uploadedFile);
            }
        }
    } catch (FileUploadException ex) {
        logger.error("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        logger.error("Error encountered while uploading file", ex);
    }
    return uploadedFile;
}

From source file:com.news.util.UploadFileUtil.java

public static String upload(HttpServletRequest request, String paramName, String fileName) {
    String result = "";
    File file;//  ww w.  j  av a  2s . co  m
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    String filePath = "";
    ///opt/apache-tomcat-7.0.59/webapps/noithat
    //filePath = getServletContext().getRealPath("") + File.separator + "test-upload" + File.separator;
    filePath = File.separator + File.separator + "opt" + File.separator + File.separator;
    filePath += "apache-tomcat-7.0.59" + File.separator + File.separator + "webapps";
    filePath += File.separator + File.separator + "noithat";
    filePath += File.separator + File.separator + "upload" + File.separator + File.separator;
    filePath += "images" + File.separator;

    //filePath = "E:" + File.separator;

    // Verify the content type
    String contentType = request.getContentType();
    System.out.println("contentType=" + contentType);
    if (contentType != null && (contentType.indexOf("multipart/form-data") >= 0)) {

        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"));

        // 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);
            System.out.println("fileItems.size()=" + fileItems.size());
            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField() && fi.getFieldName().equals(paramName)) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    int dotPos = fi.getName().lastIndexOf(".");
                    if (dotPos < 0) {
                        fileName += ".jpg";
                    } else {
                        fileName += fi.getName().substring(dotPos);
                    }
                    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);
                    System.out.println("Uploaded Filename: " + filePath + fileName + "<br>");
                    result = fileName;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:ccc.plugins.multipart.apache.MultipartForm.java

/**
 * Parse an HTTP request, extracting the file items.
 *
 * @param context The JAXRS context to parse.
 *
 * @return A list of file items.// w  ww.j a va  2s.  c om
 */
@SuppressWarnings("unchecked")
private static List<FileItem> parseFileItems(final JaxrsRequestContext context) {

    DBC.require().notNull(context);

    // Check that we have a file upload request
    final boolean isMultipart = FileUploadBase.isMultipartContent(context);
    if (!isMultipart) {
        throw new RuntimeException("Not a multipart.");
    }

    // Create a factory for disk-based file items
    final DiskFileItemFactory factory = new DiskFileItemFactory();

    // Set factory constraints
    factory.setSizeThreshold(maxInMemorySize());

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

    // Set overall request size constraint
    upload.setFileSizeMax(maxFileSize());

    try {
        return upload.parseRequest(context);
    } catch (final FileSizeLimitExceededException e) {
        throw handleTooBig(e, e.getPermittedSize());
    } catch (final SizeLimitExceededException e) {
        throw handleTooBig(e, e.getPermittedSize());
    } catch (final FileUploadException e) {
        throw new RuntimeException("Failed to parse multipart request.", e);
    }
}

From source file:beans.service.FileUploadTool.java

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

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    System.out.printf("temporary directory:%s", tmpDir);

    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));

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

    // Set overall request size constraint
    upload.setSizeMax(MaxRequestSize);/*  w w w .j a  v  a 2  s.  com*/

    // Parse the request
    try {
        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();
                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: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  w  w w.jav  a 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: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);//from  w ww . j a va 2s. co  m

    // Parse the request
    try {
        @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:jeeves.server.sources.JeevletServiceRequestFactory.java

private static Element getMultipartParams(Request req, String uploadDir, int maxUploadSize) throws Exception {

    Element params = new Element("params");

    // FIXME FileUpload - confirm only "multipart/form-data" entities must be parsed here ...
    // if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {

    // The Apache FileUpload project parses HTTP requests which
    // conform to RFC 1867, "Form-based File Upload in HTML". That
    // is, if an HTTP request is submitted using the POST method,
    // and with a content type of "multipart/form-data", then
    // FileUpload can parse that request, and get all uploaded files
    // as FileItem.

    // 1/ Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1000240); // en mmoire
    factory.setRepository(new File(uploadDir));

    // 2/ Create a new file upload handler based on the Restlet
    // FileUpload extension that will parse Restlet requests and
    // generates FileItems.
    RestletFileUpload upload = new RestletFileUpload(factory);

    upload.setFileSizeMax(maxUploadSize * 1024 * 1024);

    List<FileItem> items;//  w ww .ja v a 2 s .co m
    try {
        items = upload.parseRequest(req);// parseRepresentation(req.getEntity());

        for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) {
            FileItem item = (FileItem) it.next();

            String name = item.getFieldName();

            if (item.isFormField())
                params.addContent(new Element(name).setText(item.getString()));
            else {
                String file = item.getName();
                String type = item.getContentType();
                long size = item.getSize();
                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);
                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);

                Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem));
                params.addContent(elem);
            }
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // throw jeeves exception --> reached code ? see apache docs -
        // FileUploadBase
        throw new FileUploadTooBigEx();
    } catch (FileUploadException e) {
        // Sample Restlet ... " 

        // The message of all thrown exception is sent back to client as simple plain text
        // response.setEntity(new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN));
        // response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        // e.printStackTrace();

        // " ... now throw a JeevletException but
        // FIXME must throw Exception with a correct Status
        throw new JeevletException(e);
    }

    return params;
}

From source file:com.zlfun.framework.misc.UploadUtils.java

public static byte[] getFileBytes(HttpServletRequest request) {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // ???/*  ww w  . j  a  v a2 s .  c  om*/
    // ??
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // ??

    //  ?? 
    factory.setSizeThreshold(1024 * 1024);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    try {
        // ?
        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : list) {
            // ????
            String name = item.getFieldName();

            // ? ??  ?
            if (item.isFormField()) {
                // ? ?????? 
                String value = new String(item.getString().getBytes("iso-8859-1"), "utf-8");

                request.setAttribute(name, value);
            } // ? ??  
            else {
                /**
                 * ?? ??
                 */
                // ???
                String value = item.getName();
                // ?
                // ????
                value = java.net.URLDecoder.decode(value, "UTF-8");
                int start = value.lastIndexOf("\\");
                // ?  ??1 ???
                String filename = value.substring(start + 1);

                InputStream in = item.getInputStream();
                int length = 0;
                byte[] buf = new byte[1024];
                System.out.println("??" + item.getSize());
                // in.read(buf) ?? buf 
                while ((length = in.read(buf)) != -1) {
                    //  buf  ??  ??
                    out.write(buf, 0, length);
                }

                try {

                    if (in != null) {
                        in.close();
                    }

                } catch (IOException ex) {
                    Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
                return out.toByteArray();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    return null;

}

From source file:dk.clarin.tools.userhandle.java

@SuppressWarnings("unchecked")
public static List<FileItem> getParmList(HttpServletRequest request) throws ServletException {
    List<FileItem> items = null;
    boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request);

    if (is_multipart_formData) {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*// ww w  .ja v a 2  s  .c om
        *Set the size threshold, above which content will be stored on disk.
        */
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        /*
        * Set the temporary directory to store the uploaded files of size above threshold.
        */
        File tmpDir = new File(ToolsProperties.tempdir);
        if (!tmpDir.isDirectory()) {
            throw new ServletException("Trying to set \"" + ToolsProperties.tempdir
                    + "\" as temporary directory, but this is not a valid directory.");
        }
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            items = (List<FileItem>) uploadHandler.parseRequest(request);
        } catch (FileUploadException ex) {
            logger.error("Error encountered while parsing the request: " + ex.getMessage());
        }
    }
    return items;
}