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

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

Introduction

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

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:com.intbit.FileUploadUtil.java

public static String uploadFile(String uploadPath, HttpServletRequest request)
        throws FileUploadException, Exception {
    logger.info("FileUploadUtil::Entering FileUploadUtil#uploadFile");

    String fileName = null;/*w w w. j a v a  2 s . c  o  m*/
    logger.info("FileUploadUtil::Upload path without filename: " + uploadPath);
    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(AppConstants.TMP_FOLDER));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    // Parse the request to get file items.
    List fileItems = upload.parseRequest(request);

    // Process the uploaded file items
    Iterator i = fileItems.iterator();

    while (i.hasNext()) {
        FileItem fi = (FileItem) i.next();
        if (!(fi.isFormField())) {
            // Get the uploaded file parameters
            fileName = fi.getName();
            if (!"".equals(fileName)) {
                File uploadDir = new File(uploadPath);
                boolean result = false;
                if (!uploadDir.exists()) {
                    result = uploadDir.mkdirs();
                }
                // Write the file
                String filePath = uploadPath + File.separator + fileName;
                logger.info("FileUploadUtil::Upload path with filename" + filePath);
                File storeFile = new File(filePath);
                fi.write(storeFile);
                logger.info("FileUploadUtil::File Uploaded successfully");

            } else {
                throw new IllegalArgumentException("Filename of uploded file cannot be empty");
            }
        }
    }
    return fileName;
}

From source file:com.openmeap.util.ServletUtils.java

/**
 * @param modelManager/*from www .  j a  va2  s .c o  m*/
 * @param request
 * @param map
 * @return
 * @throws FileUploadException
 */
static final public Boolean handleFileUploads(Integer maxFileUploadSize, String fileStoragePrefix,
        HttpServletRequest request, Map<Object, Object> map) throws FileUploadException {

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    factory.setRepository(new File(fileStoragePrefix));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxFileUploadSize);

    List fileItems = upload.parseRequest(request);
    for (FileItem item : (List<FileItem>) fileItems) {
        // we'll put this in the parameter map,
        // assuming the backing that is looking for it
        // knows what to expect
        String fieldName = item.getFieldName();
        Boolean isFormField = item.isFormField();
        Long size = item.getSize();
        if (isFormField) {
            if (size > 0) {
                map.put(fieldName, new String[] { item.getString() });
            }
        } else if (!isFormField) {
            map.put(fieldName, item);
        }
    }

    return true;
}

From source file:com.mobiaware.util.UploadHelpers.java

public static File createUploadFile(final HttpServletRequest request) {
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setSizeThreshold(THRESHOLD_SIZE);
    fileItemFactory.setRepository(FileUtils.getTempDirectory());

    ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
    servletFileUpload.setFileSizeMax(MAX_FILE_SIZE);
    servletFileUpload.setSizeMax(REQUEST_SIZE);

    File file = null;//from w  ww. j  a  v  a 2  s . c o m

    try {
        FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);
        while (fileItemIterator.hasNext()) {
            FileItemStream fileItem = fileItemIterator.next();

            if (fileItem.isFormField()) {
                // ignore
            } else {
                file = File.createTempFile("liim_", null);

                InputStream is = new BufferedInputStream(fileItem.openStream());
                FileUtils.copyInputStreamToFile(is, file);
            }
        }
    } catch (IOException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } catch (FileUploadException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    }

    return file;
}

From source file:com.softwarementors.extjs.djn.router.processor.standard.form.upload.UploadFormPostRequestProcessor.java

public static ServletFileUpload createFileUploader() {
    // Create a factory for disk-based file items
    DiskFileItemFactory2 factory = new DiskFileItemFactory2();
    // Set factory constraints so that files are never written to disk
    final int MAX_UPLOAD_MEMORY_SIZE = Integer.MAX_VALUE;
    // If request size bigger than this, store files to disk
    factory.setSizeThreshold(MAX_UPLOAD_MEMORY_SIZE);
    // Avoid creating a cleaning thread which Google AppEngine will not like!
    factory.setFileCleaningTracker(null);
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Set upload handler limits
    upload.setSizeMax(MAX_UPLOAD_MEMORY_SIZE);
    upload.setFileSizeMax(MAX_UPLOAD_MEMORY_SIZE);
    return upload;
}

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

    // Parse the request
    try {/*from  www. j a  va  2 s.  c  o m*/
        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: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   www . ja va  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:fr.paris.lutece.util.http.MultipartUtil.java

/**
 * Convert a HTTP request to a {@link MultipartHttpServletRequest}
 * @param nSizeThreshold the size threshold
 * @param nRequestSizeMax the request size max
 * @param bActivateNormalizeFileName true if the file name must be normalized, false otherwise
 * @param request the HTTP request//  w  w  w.  jav  a 2s .  co m
 * @return a {@link MultipartHttpServletRequest}, null if the request does not have a multipart content
 * @throws SizeLimitExceededException exception if the file size is too big
 * @throws FileUploadException exception if an unknown error has occurred
 */
public static MultipartHttpServletRequest convert(int nSizeThreshold, long nRequestSizeMax,
        boolean bActivateNormalizeFileName, HttpServletRequest request)
        throws SizeLimitExceededException, FileUploadException {
    if (isMultipart(request)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

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

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

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

        // get encoding to be used
        String strEncoding = request.getCharacterEncoding();

        if (strEncoding == null) {
            strEncoding = EncodingService.getEncoding();
        }

        Map<String, FileItem> mapFiles = new HashMap<String, FileItem>();
        Map<String, String[]> mapParameters = new HashMap<String, String[]>();

        List<FileItem> listItems = upload.parseRequest(request);

        // Process the uploaded items
        for (FileItem item : listItems) {
            if (item.isFormField()) {
                String strValue = StringUtils.EMPTY;

                try {
                    if (item.getSize() > 0) {
                        strValue = item.getString(strEncoding);
                    }
                } catch (UnsupportedEncodingException ex) {
                    if (item.getSize() > 0) {
                        // if encoding problem, try with system encoding
                        strValue = item.getString();
                    }
                }

                // check if item of same name already in map
                String[] curParam = mapParameters.get(item.getFieldName());

                if (curParam == null) {
                    // simple form field
                    mapParameters.put(item.getFieldName(), new String[] { strValue });
                } else {
                    // array of simple form fields
                    String[] newArray = new String[curParam.length + 1];
                    System.arraycopy(curParam, 0, newArray, 0, curParam.length);
                    newArray[curParam.length] = strValue;
                    mapParameters.put(item.getFieldName(), newArray);
                }
            } else {
                // multipart file field, if the parameter filter ActivateNormalizeFileName is set to true
                //all file name will be normalize
                mapFiles.put(item.getFieldName(),
                        bActivateNormalizeFileName ? new NormalizeFileItem(item) : item);
            }
        }

        return new MultipartHttpServletRequest(request, mapFiles, mapParameters);
    }

    return null;
}

From source file:dataMappers.PictureDataMapper.java

public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request)
        throws FileUploadException, IOException, SQLException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        System.out.println("Invalid upload request");
        return;/*from  ww w  .  j  av  a2  s  . c o m*/
    }

    // Define limits for disk item
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);

    // Define limit for servlet upload
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    FileItem itemFile = null;
    int reportID = 0;

    // Get list of items in request (parameters, files etc.)
    List formItems = upload.parseRequest(request);
    Iterator iter = formItems.iterator();

    // Loop items
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            itemFile = item; // If not form field, must be item
        } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field
            try {
                System.out.println(item.getString());
                reportID = Integer.parseInt(item.getString());
            } catch (NumberFormatException e) {
                reportID = 0;
            }
        }
    }

    // This will be null if no fields were declared as image/upload.
    // Also, reportID must be > 0
    if (itemFile != null || reportID == 0) {

        try {

            // Create credentials from final vars
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);

            // Create client with credentials
            AmazonS3 s3client = new AmazonS3Client(awsCredentials);
            // Set region
            s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));

            // Set content length (size) of file
            ObjectMetadata om = new ObjectMetadata();
            om.setContentLength(itemFile.getSize());

            // Get extension for file
            String ext = FilenameUtils.getExtension(itemFile.getName());
            // Generate random filename
            String keyName = UUID.randomUUID().toString() + '.' + ext;

            // This is the actual upload command
            s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om));

            // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report.
            PreparedStatement stmt = dbconnector.getCon()
                    .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)");

            stmt.setInt(1, reportID);
            stmt.setString(2, keyName);

            stmt.executeUpdate();

            stmt.close();

        } catch (AmazonServiceException ase) {

            System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());

        } catch (AmazonClientException ace) {

            System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());

        }

    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.java

/**
 * Create an upload handler that will throw an exception if the file is too
 * large.//from   w w w.j a va  2  s  .c  om
 */
private static ServletFileUpload createUploadHandler(HttpServletRequest req, long maxFileSize) {
    File tempDir = figureTemporaryDirectory(req);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
    factory.setRepository(tempDir);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxFileSize);
    return upload;
}

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

public static String upload(HttpServletRequest request, String paramName, String fileName) {
    String result = "";
    File file;/*  w w  w.ja v a 2 s  . 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;
}