Example usage for org.apache.commons.fileupload FileItem getSize

List of usage examples for org.apache.commons.fileupload FileItem getSize

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getSize.

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:org.apache.myfaces.custom.fileupload.HtmlFileUploadRendererTest.java

public void testUploadedFileDefaultMemoryImplSerializable() throws Exception {
    String fieldName = "inputFile";
    String contentType = "someType";

    MockControl control = MockControl.createControl(FileItem.class);
    FileItem item = (FileItem) control.getMock();

    item.getName();/*from  w  w  w.j  ava 2 s .  c  o  m*/
    control.setReturnValue(fieldName, 1);
    item.getContentType();
    control.setReturnValue(contentType, 1);
    item.getSize();
    control.setReturnValue(0, 1);
    item.getInputStream();
    control.setReturnValue(new InputStream() {
        public int read() throws IOException {
            return -1;
        }
    }, 1);

    item.delete();
    control.setVoidCallable(1);

    control.replay();

    UploadedFileDefaultMemoryImpl original = new UploadedFileDefaultMemoryImpl(item);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(out);
    oos.writeObject(original);
    oos.close();

    byte[] serializedArray = out.toByteArray();
    InputStream in = new ByteArrayInputStream(serializedArray);
    ObjectInputStream ois = new ObjectInputStream(in);
    UploadedFileDefaultMemoryImpl copy = (UploadedFileDefaultMemoryImpl) ois.readObject();

    assertEquals(original.getName(), copy.getName());
    assertEquals(original.getContentType(), copy.getContentType());
    assertEquals(copy.getSize(), 0);

    copy.getStorageStrategy().deleteFileContents();
}

From source file:org.apache.myfaces.custom.fileupload.UploadedFileDefaultMemoryImpl.java

public UploadedFileDefaultMemoryImpl(final FileItem fileItem) throws IOException {
    super(fileItem.getName(), fileItem.getContentType());
    int sizeInBytes = (int) fileItem.getSize();
    bytes = new byte[sizeInBytes];
    this.fileItem = fileItem;
    fileItem.getInputStream().read(bytes);
    this.storageStrategy = new DefaultMemoryStorageStrategy();
}

From source file:org.apache.ofbiz.webapp.event.ServiceEventHandler.java

/**
 * @see org.apache.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from  w ww .  j ava  2s  .c  o m*/
public String invoke(Event event, RequestMap requestMap, HttpServletRequest request,
        HttpServletResponse response) throws EventHandlerException {
    // make sure we have a valid reference to the Service Engine
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    if (dispatcher == null) {
        throw new EventHandlerException("The local service dispatcher is null");
    }
    DispatchContext dctx = dispatcher.getDispatchContext();
    if (dctx == null) {
        throw new EventHandlerException("Dispatch context cannot be found");
    }

    // get the details for the service(s) to call
    String mode = SYNC;
    String serviceName = null;

    if (UtilValidate.isEmpty(event.path)) {
        mode = SYNC;
    } else {
        mode = event.path;
    }

    // make sure we have a defined service to call
    serviceName = event.invoke;
    if (serviceName == null) {
        throw new EventHandlerException("Service name (eventMethod) cannot be null");
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module);

    // some needed info for when running the service
    Locale locale = UtilHttp.getLocale(request);
    TimeZone timeZone = UtilHttp.getTimeZone(request);
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");

    // get the service model to generate context
    ModelService model = null;

    try {
        model = dctx.getModelService(serviceName);
    } catch (GenericServiceException e) {
        throw new EventHandlerException("Problems getting the service model", e);
    }

    if (model == null) {
        throw new EventHandlerException("Problems getting the service model");
    }

    if (Debug.verboseOn()) {
        Debug.logVerbose("[Processing]: SERVICE Event", module);
        Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module);
    }

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> multiPartMap = new HashMap<String, Object>();
    if (isMultiPart) {
        // get the http upload configuration
        String maxSizeStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.size", "-1",
                dctx.getDelegator());
        long maxUploadSize = -1;
        try {
            maxUploadSize = Long.parseLong(maxSizeStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1",
                    module);
            maxUploadSize = -1;
        }
        // get the http size threshold configuration - files bigger than this will be
        // temporarly stored on disk during upload
        String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general",
                "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
        int sizeThreshold = 10240; // 10K
        try {
            sizeThreshold = Integer.parseInt(sizeThresholdStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K",
                    module);
            sizeThreshold = -1;
        }
        // directory used to temporarily store files that are larger than the configured size threshold
        String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general",
                "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
        String encoding = request.getCharacterEncoding();
        // check for multipart content types which may have uploaded items

        ServletFileUpload upload = new ServletFileUpload(
                new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));

        // create the progress listener and add it to the session
        FileUploadProgressListener listener = new FileUploadProgressListener();
        upload.setProgressListener(listener);
        session.setAttribute("uploadProgressListener", listener);

        if (encoding != null) {
            upload.setHeaderEncoding(encoding);
        }
        upload.setSizeMax(maxUploadSize);

        List<FileItem> uploadedItems = null;
        try {
            uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
        } catch (FileUploadException e) {
            throw new EventHandlerException("Problems reading uploaded data", e);
        }
        if (uploadedItems != null) {
            for (FileItem item : uploadedItems) {
                String fieldName = item.getFieldName();
                //byte[] itemBytes = item.get();
                /*
                Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " +
                    item.getContentType() + " FF: " + item.isFormField(), module);
                */
                if (item.isFormField() || item.getName() == null) {
                    if (multiPartMap.containsKey(fieldName)) {
                        Object mapValue = multiPartMap.get(fieldName);
                        if (mapValue instanceof List<?>) {
                            checkList(mapValue, Object.class).add(item.getString());
                        } else if (mapValue instanceof String) {
                            List<String> newList = new LinkedList<String>();
                            newList.add((String) mapValue);
                            newList.add(item.getString());
                            multiPartMap.put(fieldName, newList);
                        } else {
                            Debug.logWarning("Form field found [" + fieldName + "] which was not handled!",
                                    module);
                        }
                    } else {
                        if (encoding != null) {
                            try {
                                multiPartMap.put(fieldName, item.getString(encoding));
                            } catch (java.io.UnsupportedEncodingException uee) {
                                Debug.logError(uee, "Unsupported Encoding, using deafault", module);
                                multiPartMap.put(fieldName, item.getString());
                            }
                        } else {
                            multiPartMap.put(fieldName, item.getString());
                        }
                    }
                } else {
                    String fileName = item.getName();
                    if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
                        // get just the file name IE and other browsers also pass in the local path
                        int lastIndex = fileName.lastIndexOf('\\');
                        if (lastIndex == -1) {
                            lastIndex = fileName.lastIndexOf('/');
                        }
                        if (lastIndex > -1) {
                            fileName = fileName.substring(lastIndex + 1);
                        }
                    }
                    multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
                    multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize()));
                    multiPartMap.put("_" + fieldName + "_fileName", fileName);
                    multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
                }
            }
        }
    }

    // store the multi-part map as an attribute so we can access the parameters
    request.setAttribute("multiPartMap", multiPartMap);

    Map<String, Object> rawParametersMap = UtilHttp.getCombinedMap(request);
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();

    // we have a service and the model; build the context
    Map<String, Object> serviceContext = new HashMap<String, Object>();
    for (ModelParam modelParam : model.getInModelParamList()) {
        String name = modelParam.name;

        // don't include userLogin, that's taken care of below
        if ("userLogin".equals(name))
            continue;
        // don't include locale, that is also taken care of below
        if ("locale".equals(name))
            continue;
        // don't include timeZone, that is also taken care of below
        if ("timeZone".equals(name))
            continue;

        Object value = null;
        if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
            Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap,
                    modelParam.stringMapPrefix, null);
            value = paramMap;
            if (Debug.verboseOn())
                Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module);
        } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
            List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap,
                    modelParam.stringListSuffix, null);
            value = paramList;
        } else {
            // first check the multi-part map
            value = multiPartMap.get(name);

            // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request
                        .getAttribute(UtilValidate.isEmpty(modelParam.requestAttributeName) ? name
                                : modelParam.requestAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // check the request parameters
            if (UtilValidate.isEmpty(value)) {
                ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session,
                        serviceName, dctx.getDelegator());

                // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up
                if ("any".equals(modelParam.allowHtml)) {
                    value = request.getParameter(name);
                } else {
                    // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc
                    value = rawParametersMap.get(name);
                }

                // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
                if (value == null) {
                    value = UtilHttp.makeParamValueFromComposite(request, name, locale);
                }
            }

            // then session
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getSession()
                        .getAttribute(UtilValidate.isEmpty(modelParam.sessionAttributeName) ? name
                                : modelParam.sessionAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // no field found
            if (value == null) {
                //still null, give up for this one
                continue;
            }

            if (value instanceof String && ((String) value).length() == 0) {
                // interpreting empty fields as null values for each in back end handling...
                value = null;
            }
        }
        // set even if null so that values will get nulled in the db later on
        serviceContext.put(name, value);
    }

    // get only the parameters for this service - converted to proper type
    // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any
    List<Object> errorMessages = new LinkedList<Object>();
    serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone,
            locale);
    if (errorMessages.size() > 0) {
        // uh-oh, had some problems...
        request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages);
        return "error";
    }

    // include the UserLogin value object
    if (userLogin != null) {
        serviceContext.put("userLogin", userLogin);
    }

    // include the Locale object
    if (locale != null) {
        serviceContext.put("locale", locale);
    }

    // include the TimeZone object
    if (timeZone != null) {
        serviceContext.put("timeZone", timeZone);
    }

    // invoke the service
    Map<String, Object> result = null;
    try {
        if (ASYNC.equalsIgnoreCase(mode)) {
            dispatcher.runAsync(serviceName, serviceContext);
        } else {
            result = dispatcher.runSync(serviceName, serviceContext);
        }
    } catch (ServiceAuthException e) {
        // not logging since the service engine already did
        request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        return "error";
    } catch (ServiceValidationException e) {
        // not logging since the service engine already did
        request.setAttribute("serviceValidationException", e);
        if (e.getMessageList() != null) {
            request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList());
        } else {
            request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        }
        return "error";
    } catch (GenericServiceException e) {
        Debug.logError(e, "Service invocation error", module);
        throw new EventHandlerException("Service invocation error", e.getNested());
    }

    String responseString = null;

    if (result == null) {
        responseString = ModelService.RESPOND_SUCCESS;
    } else {

        if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) {
            responseString = ModelService.RESPOND_SUCCESS;
        } else {
            responseString = (String) result.get(ModelService.RESPONSE_MESSAGE);
        }

        // set the messages in the request; this will be picked up by messages.ftl and displayed
        request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST));
        request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP));
        request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));

        request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST));
        request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE));

        // set the results in the request
        for (Map.Entry<String, Object> rme : result.entrySet()) {
            String resultKey = rme.getKey();
            Object resultValue = rme.getValue();

            if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey)
                    && !ModelService.SUCCESS_MESSAGE.equals(resultKey)
                    && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) {
                request.setAttribute(resultKey, resultValue);
            }
        }
    }

    if (Debug.verboseOn())
        Debug.logVerbose("[Event Return]: " + responseString, module);
    return responseString;
}

From source file:org.apache.solr.servlet.SolrRequestParsers.java

public SolrParams parseParamsAndFillStreams(final HttpServletRequest req, ArrayList<ContentStream> streams)
        throws Exception {
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                "Not multipart content! " + req.getContentType());
    }//www .java2  s . c o  m

    MultiMapSolrParams params = SolrRequestParsers.parseQueryString(req.getQueryString());

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

    // Set factory constraints
    // TODO - configure factory.setSizeThreshold(yourMaxMemorySize);
    // TODO - configure factory.setRepository(yourTempDirectory);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(uploadLimitKB * 1024);

    // Parse the request
    List items = upload.parseRequest(req);
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        // If its a form field, put it in our parameter map
        if (item.isFormField()) {
            MultiMapSolrParams.addParam(item.getFieldName(), item.getString(), params.getMap());
        }
        // Add the stream
        else {
            System.out.println(item.getFieldName() + "===" + item.getSize());
            streams.add(new FileItemContentStream(item));
        }
    }
    return params;
}

From source file:org.apache.tapestry5.upload.internal.services.UploadedFileItemTest.java

@Test
public void sizeIsFileItemSize() throws Exception {
    FileItem item = newMock(FileItem.class);
    UploadedFileItem uploadedFile = new UploadedFileItem(item);

    expect(item.getSize()).andReturn(66l);

    replay();//from  ww  w.ja v a2 s .  co  m

    assertEquals(uploadedFile.getSize(), 66);

    verify();
}

From source file:org.apache.wicket.protocol.http.servlet.MultipartServletWebRequestImpl.java

@Override
public MultipartServletWebRequest newMultipartWebRequest(Bytes maxSize, String upload)
        throws FileUploadException {
    // FIXME mgrigorov: Why these checks are made here ?!
    // Why they are not done also at org.apache.wicket.protocol.http.servlet.MultipartServletWebRequestImpl.newMultipartWebRequest(org.apache.wicket.util.lang.Bytes, java.lang.String, org.apache.wicket.util.upload.FileItemFactory)() ?
    // Why there is no check that the summary of all files' sizes is less than the set maxSize ?
    // Setting a breakpoint here never breaks with the standard upload examples.

    Bytes fileMaxSize = getFileMaxSize();
    for (Map.Entry<String, List<FileItem>> entry : files.entrySet()) {
        List<FileItem> fileItems = entry.getValue();
        for (FileItem fileItem : fileItems) {
            if (fileMaxSize != null && fileItem.getSize() > fileMaxSize.bytes()) {
                String fieldName = entry.getKey();
                FileUploadException fslex = new FileUploadBase.FileSizeLimitExceededException("The field '"
                        + fieldName + "' exceeds its maximum permitted size of '" + maxSize + "' characters.",
                        fileItem.getSize(), fileMaxSize.bytes());
                throw fslex;
            }/*  ww  w . j av  a2  s  . com*/
        }
    }
    return this;
}

From source file:org.appcelerator.transport.UploadTransportServlet.java

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getMethod().equalsIgnoreCase("POST")) {
        // paranoia check -we don't accept urlencoded transfers which are very bad performance wise
        if (false == ServletFileUpload.isMultipartContent(request)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "must be 'multipart/form-data'");
            return;
        }//  ww  w.ja v a 2  s  .c om

        String type = null;
        String callback = null;
        long size = 0L;
        // String instanceid = null;
        IMessageDataObject data = MessageUtils.createMessageDataObject();

        try {
            ServletFileUpload upload = new ServletFileUpload(fileFactory);
            List items = upload.parseRequest(request);
            for (Iterator i = items.iterator(); i.hasNext();) {
                FileItem item = (FileItem) i.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equals("callback")) {
                        callback = item.getString();
                        continue;
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString();
                        continue;
                    } else if (item.getFieldName().equals("instanceid")) {
                        //instanceid = item.getString();
                        continue;
                    }
                    // place it in the data payload
                    data.put(item.getFieldName(), item.getString());
                } else {
                    File f = null;
                    if (tempDirectory != null) {
                        f = File.createTempFile("sup", ".tmp", tempDirectory);
                    } else {
                        f = File.createTempFile("sup", ".tmp");
                    }

                    f.deleteOnExit();

                    // write out the temporary file
                    item.write(f);

                    size = item.getSize();

                    IMessageDataObject filedata = MessageUtils.createMessageDataObject();

                    filedata.put("file", f.getAbsolutePath());
                    filedata.put("size", size);
                    filedata.put("contentType", item.getContentType());
                    filedata.put("fieldName", item.getFieldName());
                    filedata.put("fileName", item.getName());

                    data.put("filedata", filedata);
                }
            }

            // required parameter type
            if (type == null || type.equals("")) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing 'type' parameter");
                return;
            }
        } catch (Throwable fe) {
            fe.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fe.getMessage());
            return;
        }

        String scope = request.getParameter("scope");
        String version = request.getParameter("version");

        if (scope == null) {
            scope = "appcelerator";
        }
        if (version == null) {
            version = "1.0";
        }

        // create a message
        Message msg = new Message();
        msg.setUser(request.getUserPrincipal());
        msg.setSession(request.getSession());
        msg.setServletRequest(request);
        msg.setType(type);
        msg.setData(data);
        msg.setAddress(InetAddress.getByName(request.getRemoteAddr()));
        msg.setScope(scope);
        msg.setVersion(version);

        // send the data
        ArrayList<Message> responses = new ArrayList<Message>();
        try {
            ServiceRegistry.dispatch(msg, responses);
        } catch (Exception ex) {
            LOG.error("error dispatching upload message: " + msg, ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
        response.setDateHeader("Expires", System.currentTimeMillis() - TimeUtil.ONE_YEAR);
        response.setContentType("text/html;charset=UTF-8");

        // optionally, invoke a callback function/message on upload in the client
        if (callback != null || !responses.isEmpty()) {
            StringBuilder code = new StringBuilder();
            code.append("<html><head><script>");

            if (callback != null) {
                if (callback.startsWith("l:") || callback.startsWith("local:") || callback.startsWith("r:")
                        || callback.startsWith("remote:")) {
                    code.append(makeMessage(callback, "{size:" + size + "}", scope, version));
                } else {
                    // a javascript function to call
                    code.append("window.parent.").append(callback).append("();");
                }
            }

            for (Message m : responses) {
                code.append(makeMessage(m.getType(), m.getData().toDataString(), m.getScope(), m.getVersion()));
            }

            code.append("</script></head><body></body></html>");

            // send the response
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().print(code.toString());
        } else {
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
        }
    } else {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "method was: " + request.getMethod());
    }
}

From source file:org.axe.helper.mvc.FormRequestHelper.java

/**
 * //from  w  w  w . j  a  va  2 s. co m
 */
public static void initParam(Param param, HttpServletRequest request, String requestPath, String mappingPath) {
    List<FormParam> formParamList = new ArrayList<>();
    List<FileParam> fileParamList = new ArrayList<>();
    try {
        //????
        Map<String, List<FileItem>> fileItemListMap = servletFileUpload.parseParameterMap(request);
        if (CollectionUtil.isNotEmpty(fileItemListMap)) {
            for (Map.Entry<String, List<FileItem>> fileItemListEntry : fileItemListMap.entrySet()) {
                String fieldName = fileItemListEntry.getKey();
                List<FileItem> fileItemList = fileItemListEntry.getValue();
                if (CollectionUtil.isNotEmpty(fileItemList)) {
                    for (FileItem fileItem : fileItemList) {
                        if (fileItem.isFormField()) {
                            String fieldValue = fileItem.getString("UTF-8");
                            formParamList.add(new FormParam(fieldName, fieldValue));
                        } else {
                            String fileName = FileUtil
                                    .getRealFileName(new String(fileItem.getName().getBytes(), "UTF-8"));
                            if (StringUtil.isNotEmpty(fileName)) {
                                long fileSize = fileItem.getSize();
                                String contentType = fileItem.getContentType();
                                InputStream inputStream = fileItem.getInputStream();
                                fileParamList.add(
                                        new FileParam(fieldName, fileName, fileSize, contentType, inputStream));
                            }
                        }
                    }
                }
            }
        }

        //?url?
        formParamList.addAll(RequestUtil.parseParameter(request, requestPath, mappingPath));
    } catch (Exception e) {
        LOGGER.error("create param failed", e);
        throw new RuntimeException(e);
    }
    param.init(null, formParamList, fileParamList, null);
}

From source file:org.bibsonomy.webapp.controller.ajax.DocumentsController.java

/**
 * This method handles file upload to a temporary directory 
 * @param command/*from   www  .  j a  v  a  2s  . c  om*/
 * @return
 */
private String uploadFile(AjaxDocumentCommand command, Locale locale) {
    log.debug("Start uploading file");

    /*
     * the uploaded file
     */
    final FileItem fileItem = command.getFile().getFileItem();
    final int fileID = command.getFileID();
    /*
     * unsupported file extensions
     */
    if (!StringUtils.matchExtension(fileItem.getName(), FileUploadInterface.fileUploadExt)) {
        return getXmlError("error.upload.failed.filetype", new Object[] { ALLOWED_EXTENSIONS }, fileID,
                fileItem.getName(), locale);
    }

    /*
     * wrong file size
     */
    final long size = fileItem.getSize();
    if (size >= maxFileSize) {
        return getXmlError("error.upload.failed.size", new Object[] { maxFileSizeMB }, fileID,
                fileItem.getName(), locale);
    } else if (size == 0) {
        return getXmlError("error.upload.failed.size0", null, fileID, fileItem.getName(), locale);
    }

    final File uploadFile;
    String fileHash = FileUtil.getRandomFileHash(fileItem.getName());
    if (command.isTemp()) { // /editPublication
        uploadFile = new File(tempPath + fileHash);
    } else { // /bibtex/....
        uploadFile = new File(FileUtil.getFilePath(docPath, fileHash));
    }
    final String md5Hash = HashUtils.getMD5Hash(fileItem.get());
    try {
        fileItem.write(uploadFile);
    } catch (final Exception ex) {
        log.error("Could not write uploaded file.", ex);
        return getXmlError("error.500", null, fileID, fileItem.getName(), locale);
    }

    if (!command.isTemp()) {
        final Document document = new Document();
        document.setFileName(fileItem.getName());
        document.setFileHash(fileHash);
        document.setMd5hash(md5Hash);
        document.setUserName(command.getContext().getLoginUser().getName());

        /*
         * add document to the data base
         */
        logic.createDocument(document, command.getIntraHash());

        /*
         * clear fileHash (randomFileName), so only md5Hash over the file content will be sent back
         */
        fileHash = "";
    }

    return "<root><status>ok</status><fileid>" + fileID + "</fileid><filehash>" + md5Hash + fileHash
            + "</filehash><filename>" + fileItem.getName() + "</filename></root>";
}

From source file:org.bonitasoft.console.common.server.servlet.TenantFileUploadServlet.java

@Override
protected void checkUploadSize(final HttpServletRequest request, final FileItem item)
        throws FileTooBigException {
    final long contentSize = item.getSize();
    final long maxSize = getDefaultFormProperties(getAPISession(request).getTenantId()).getAttachmentMaxSize();
    if (contentSize > maxSize * 1048576) {
        final String errorMessage = "file " + item.getName() + " too big !";
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, errorMessage);
        }//from  www .  j  a v  a  2  s  . co  m
        throw new FileTooBigException(errorMessage, item.getName(), String.valueOf(maxSize));
    }
}