Java 类org.apache.commons.fileupload.FileUploadBase 实例源码

项目:WidgetStore    文件:ServletRequestContext.java   
/**
 * Retrieve the content length of the request.
 *
 * @return The content length of the request.
 * @since 1.3
 */
public long contentLength() {
    long size;
    try {
        size = Long.parseLong(request.getHeader(FileUploadBase.CONTENT_LENGTH));
    } catch (NumberFormatException e) {
        size = request.getContentLength();
    }
    return size;
}
项目:WidgetStore    文件:PortletRequestContext.java   
/**
 * Retrieve the content length of the request.
 *
 * @return The content length of the request.
 * @since 1.3
 */
public long contentLength() {
    long size;
    try {
        size = Long.parseLong(request.getProperty(FileUploadBase.CONTENT_LENGTH));
    } catch (NumberFormatException e) {
        size = request.getContentLength();
    }
    return size;
}
项目:struts2    文件:JakartaStreamMultiPartRequest.java   
/**
 * Add a file skipped message notification for action messages.
 *
 * @param fileName file name
 * @param request the servlet request
 */
private void addFileSkippedError(String fileName, HttpServletRequest request) {
    String exceptionMessage = "Skipped file " + fileName + "; request size limit exceeded.";
    FileSizeLimitExceededException exception = new FileUploadBase.FileSizeLimitExceededException(exceptionMessage, getRequestSize(request), maxSize);
    String message = buildErrorMessage(exception, new Object[]{fileName, getRequestSize(request), maxSize});
    if (!errors.contains(message)) {
        errors.add(message);
    }
}
项目:cattle    文件:DefaultApiRequestParser.java   
protected Map<String, String[]> parseParams(ApiRequest apiRequest, HttpServletRequest request) throws IOException {
    try {
        Map<String, String[]> multiPart = parseMultipart(request);

        return multiPart == null ? request.getParameterMap() : multiPart;
    } catch (IOException e) {
        if (e.getCause() instanceof FileUploadBase.SizeLimitExceededException)
            throw new ClientVisibleException(ResponseCodes.REQUEST_ENTITY_TOO_LARGE);
        throw e;
    }
}
项目:cim    文件:HttpServFileUpload.java   
public static final boolean isMultipartContent(HttpRequest request) {
    String method = request.getRequestLine().getMethod();
    if (!POST_METHOD.equalsIgnoreCase(method)) {
        return false;
    }
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return false;
    }
    return FileUploadBase.isMultipartContent(new HttpServRequestContext(
            (HttpEntityEnclosingRequest) request));
}
项目:AndroidWebServ    文件:HttpServFileUpload.java   
public static final boolean isMultipartContent(HttpRequest request) {
    String method = request.getRequestLine().getMethod();
    if (!POST_METHOD.equalsIgnoreCase(method)) {
        return false;
    }
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return false;
    }
    return FileUploadBase.isMultipartContent(new HttpServRequestContext(
            (HttpEntityEnclosingRequest) request));
}
项目:gdapi-java-server    文件:DefaultApiRequestParser.java   
@SuppressWarnings("unchecked")
protected Map<String,Object> parseParams(ApiRequest apiRequest, HttpServletRequest request) throws IOException {
    try {
        Map<String,Object> multiPart = parseMultipart(request);

        return multiPart == null ? request.getParameterMap() : multiPart;
    } catch ( IOException e ) {
        if ( e.getCause() instanceof FileUploadBase.SizeLimitExceededException )
            throw new ClientVisibleException(ResponseCodes.REQUEST_ENTITY_TOO_LARGE);
        throw e;
    }
}
项目:spring-rythm    文件:CommonsMultipartResolver.java   
@Override
public boolean isMultipart(HttpServletRequest request) {
    // support HTTP PUT operation
    String method = request.getMethod().toLowerCase();
    if (S.neq("post", method) && S.neq("put", method)) {
        return false;
    }
    return FileUploadBase.isMultipartContent(new ServletRequestContext(request));
}
项目:vraptor4    文件:CommonsUploadMultipartObserverTest.java   
@Test
public void shouldValidateWhenSizeLimitExceededExceptionOccurs() throws Exception {
    when(event.getMethod()).thenReturn(uploadMethodController);

    when(observer.createServletFileUpload(config)).thenReturn(servletFileUpload);
    when(servletFileUpload.parseRequest(request)).thenThrow(new FileUploadBase.SizeLimitExceededException("", 3L, 2L));

    observer.upload(event, request, config, validator);

    verify(validator).add(any(I18nMessage.class));
}
项目:vraptor4    文件:CommonsUploadMultipartObserverTest.java   
@Test
public void shouldValidateWhenSizeLimitExceededExceptionOccursFromAnnotation() throws Exception {
    when(event.getMethod()).thenReturn(uploadMethodControllerWithAnnotation);

    when(observer.createServletFileUpload(config)).thenReturn(servletFileUpload);
    when(servletFileUpload.parseRequest(request)).thenThrow(new FileUploadBase.SizeLimitExceededException("", 3L, 2L));

    observer.upload(event, request, config, validator);

    verify(servletFileUpload).setFileSizeMax(10);
    verify(servletFileUpload).setSizeMax(20);
}
项目:ch-inofix-timetracker    文件:ImportTaskRecordsMVCActionCommand.java   
protected void addTempFileEntry(ActionRequest actionRequest, String folderName) throws Exception {

        _log.info("addTempFileEntry()");

        UploadPortletRequest uploadPortletRequest = _portal.getUploadPortletRequest(actionRequest);

        checkExceededSizeLimit(uploadPortletRequest);

        long groupId = ParamUtil.getLong(actionRequest, "groupId");

        deleteTempFileEntry(groupId, folderName);

        InputStream inputStream = null;

        try {
            String sourceFileName = uploadPortletRequest.getFileName("file");

            inputStream = uploadPortletRequest.getFileAsStream("file");

            String contentType = uploadPortletRequest.getContentType("file");

            _layoutService.addTempFileEntry(groupId, folderName, sourceFileName, inputStream, contentType);
        } catch (Exception e) {
            UploadException uploadException = (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION);

            if (uploadException != null) {
                Throwable cause = uploadException.getCause();

                if (cause instanceof FileUploadBase.IOFileUploadException) {
                    if (_log.isInfoEnabled()) {
                        _log.info("Temporary upload was cancelled");
                    }
                }

                if (uploadException.isExceededFileSizeLimit()) {
                    throw new FileSizeException(cause);
                }

                if (uploadException.isExceededUploadRequestSizeLimit()) {
                    throw new UploadRequestSizeException(cause);
                }
            } else {
                throw e;
            }
        } finally {
            StreamUtil.cleanUp(inputStream);
        }
    }
项目:ch-inofix-contact-manager    文件:ImportContactsMVCActionCommand.java   
protected void addTempFileEntry(ActionRequest actionRequest, String folderName) throws Exception {

        _log.info("addTempFileEntry()");

        UploadPortletRequest uploadPortletRequest = _portal.getUploadPortletRequest(actionRequest);

        checkExceededSizeLimit(uploadPortletRequest);

        long groupId = ParamUtil.getLong(actionRequest, "groupId");

        deleteTempFileEntry(groupId, folderName);

        InputStream inputStream = null;

        try {
            String sourceFileName = uploadPortletRequest.getFileName("file");

            inputStream = uploadPortletRequest.getFileAsStream("file");

            String contentType = uploadPortletRequest.getContentType("file");

            _layoutService.addTempFileEntry(groupId, folderName, sourceFileName, inputStream, contentType);
        } catch (Exception e) {
            UploadException uploadException = (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION);

            if (uploadException != null) {
                Throwable cause = uploadException.getCause();

                if (cause instanceof FileUploadBase.IOFileUploadException) {
                    if (_log.isInfoEnabled()) {
                        _log.info("Temporary upload was cancelled");
                    }
                }

                if (uploadException.isExceededFileSizeLimit()) {
                    throw new FileSizeException(cause);
                }

                if (uploadException.isExceededUploadRequestSizeLimit()) {
                    throw new UploadRequestSizeException(cause);
                }
            } else {
                throw e;
            }
        } finally {
            StreamUtil.cleanUp(inputStream);
        }
    }
项目:ch-inofix-data-manager    文件:ImportMeasurementsMVCActionCommand.java   
protected void addTempFileEntry(ActionRequest actionRequest, String folderName) throws Exception {

        _log.info("addTempFileEntry()");

        UploadPortletRequest uploadPortletRequest = _portal.getUploadPortletRequest(actionRequest);

        checkExceededSizeLimit(uploadPortletRequest);

        long groupId = ParamUtil.getLong(actionRequest, "groupId");

        deleteTempFileEntry(groupId, folderName);

        InputStream inputStream = null;

        try {
            String sourceFileName = uploadPortletRequest.getFileName("file");

            inputStream = uploadPortletRequest.getFileAsStream("file");

            String contentType = uploadPortletRequest.getContentType("file");

            _layoutService.addTempFileEntry(groupId, folderName, sourceFileName, inputStream, contentType);
        } catch (Exception e) {
            UploadException uploadException = (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION);

            if (uploadException != null) {
                Throwable cause = uploadException.getCause();

                if (cause instanceof FileUploadBase.IOFileUploadException) {
                    if (_log.isInfoEnabled()) {
                        _log.info("Temporary upload was cancelled");
                    }
                }

                if (uploadException.isExceededFileSizeLimit()) {
                    throw new FileSizeException(cause);
                }

                if (uploadException.isExceededUploadRequestSizeLimit()) {
                    throw new UploadRequestSizeException(cause);
                }
            } else {
                throw e;
            }
        } finally {
            StreamUtil.cleanUp(inputStream);
        }
    }
项目:tkhoon    文件:UploadHelper.java   
public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception {
    // 定义参数列表
    List<Object> paramList = new ArrayList<Object>();
    // 创建两个对象,分别对应 普通字段 与 文件字段
    Map<String, String> fieldMap = new HashMap<String, String>();
    List<Multipart> multipartList = new ArrayList<Multipart>();
    // 获取并遍历表单项
    List<FileItem> fileItemList;
    try {
        fileItemList = fileUpload.parseRequest(request);
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // 异常转换(抛出自定义异常)
        throw new UploadException(e);
    }
    for (FileItem fileItem : fileItemList) {
        // 分两种情况处理表单项
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            // 处理普通字段
            String fieldValue = fileItem.getString(FrameworkConstant.DEFAULT_CHARSET);
            fieldMap.put(fieldName, fieldValue);
        } else {
            // 处理文件字段
            String originalFileName = FileUtil.getRealFileName(fileItem.getName());
            String uploadedFileName = FileUtil.getEncodedFileName(originalFileName);
            String contentType = fileItem.getContentType();
            long fileSize = fileItem.getSize();
            InputStream inputSteam = fileItem.getInputStream();
            // 创建 Multipart 对象,并将其添加到 multipartList 中
            Multipart multipart = new Multipart(uploadedFileName, contentType, fileSize, inputSteam);
            multipartList.add(multipart);
            // 将所上传文件的文件名存入 fieldMap 中
            fieldMap.put(fieldName, uploadedFileName);
        }
    }
    // 初始化参数列表
    paramList.add(fieldMap);
    if (multipartList.size() > 1) {
        paramList.add(multipartList);
    } else if (multipartList.size() == 1) {
        paramList.add(multipartList.get(0));
    } else {
        paramList.add(null);
    }
    // 返回参数列表
    return paramList;
}
项目:AndServer    文件:HttpRequestParser.java   
/**
 * Whether to allow the RequestBody with the request.
 */
public static boolean isMultipartContentRequest(HttpRequest request) {
    if (!(request instanceof HttpEntityEnclosingRequest)) return false;
    HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;
    return isAllowRequestBody(request) && FileUploadBase.isMultipartContent(new HttpUploadContext(enclosingRequest));
}
项目:Brutusin-RPC    文件:RpcServlet.java   
/**
 *
 * @param req
 * @param rpcRequest
 * @param service
 * @return
 * @throws Exception
 */
private Map<String, InputStream> getStreams(HttpServletRequest req, RpcRequest rpcRequest, HttpAction service) throws Exception {
    if (!FileUploadBase.isMultipartContent(new ServletRequestContext(req))) {
        return null;
    }
    int streamsNumber = getInputStreamsNumber(rpcRequest, service);
    boolean isResponseStreamed = service.isBinaryResponse();
    FileItemIterator iter = (FileItemIterator) req.getAttribute(REQ_ATT_MULTIPART_ITERATOR);
    int count = 0;
    final Map<String, InputStream> map = new HashMap();
    final File tempDirectory;
    if (streamsNumber > 1 || streamsNumber == 1 && isResponseStreamed) {
        tempDirectory = createTempUploadDirectory();
        req.setAttribute(REQ_ATT_TEMPORARY_FOLDER, tempDirectory);
    } else {
        tempDirectory = null;
    }
    FileItemStream item = (FileItemStream) req.getAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM);
    long availableLength = RpcConfig.getInstance().getMaxRequestSize();
    while (item != null) {
        count++;
        long maxLength = Math.min(availableLength, RpcConfig.getInstance().getMaxFileSize());
        if (count < streamsNumber || isResponseStreamed) { // if response is streamed all inputstreams have to be readed first
            File file = new File(tempDirectory, item.getFieldName());
            FileOutputStream fos = new FileOutputStream(file);
            try {
                Miscellaneous.pipeSynchronously(new LimitedLengthInputStream(item.openStream(), maxLength), fos);
            } catch (MaxLengthExceededException ex) {
                if (maxLength == RpcConfig.getInstance().getMaxFileSize()) {
                    throw new MaxLengthExceededException("Upload part '" + item.getFieldName() + "' exceeds maximum length (" + RpcConfig.getInstance().getMaxFileSize() + " bytes)", RpcConfig.getInstance().getMaxFileSize());
                } else {
                    throw new MaxLengthExceededException("Request exceeds maximum length (" + RpcConfig.getInstance().getMaxRequestSize() + " bytes)", RpcConfig.getInstance().getMaxRequestSize());
                }
            }
            map.put(item.getFieldName(), new MetaDataInputStream(new FileInputStream(file), item.getName(), item.getContentType(), file.length(), null));
            availableLength -= file.length();
        } else if (count == streamsNumber) {
            map.put(item.getFieldName(), new MetaDataInputStream(new LimitedLengthInputStream(item.openStream(), maxLength), item.getName(), item.getContentType(), null, null));
            break;
        }
        req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item);
        if (iter.hasNext()) {
            item = iter.next();
        } else {
            item = null;
        }
    }
    if (count != streamsNumber) {
        throw new IllegalArgumentException("Invalid multipart request received. Number of uploaded files (" + count + ") does not match expected (" + streamsNumber + ")");
    }
    return map;
}
项目:testeverything    文件:UploadHelper.java   
/**
 * 创建 multipart 请求参数列表
 */
public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception {
    List<Object> paramList = new ArrayList<>();
    // 创建两个对象,分别对应 普通字段 与 文件字段
    Map<String, Object> fieldMap = new HashMap<>();
    List<Multipart> multipartList = new ArrayList<>();
    // 获取并遍历表单项
    List<FileItem> fileItemList;
    try {
        fileItemList = fileUpload.parseRequest(request);
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        throw new UploadException(e);
    }

    for (FileItem fileItem : fileItemList) {
        // 分两种情况处理表单项
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            // 处理普通字段
            String fileValue = fileItem.getString(FrameworkConstant.UTF_8);
            fieldMap.put(fieldName, fileValue);
        } else {
            // 处理文件字段
            String fileName = FileUtil.getRealFileName(fileItem.getName());
            if (StringUtil.isNotEmpty(fileName)) {
                long fileSize = fileItem.getSize();
                String contentType = fileItem.getContentType();
                InputStream inputSteam = fileItem.getInputStream();
                // 创建 Multipart 对象,并将其添加到 multipartList 中
                Multipart multipart = new Multipart(fieldName, fileName, fileSize, contentType, inputSteam);
                multipartList.add(multipart);
            }
        }
    }

    // 初始化参数列表
    paramList.add(new Params(fieldMap));
    paramList.add(new Multiparts(multipartList));
    // 返回参数列表
    return paramList;
}
项目:nexus-public    文件:HttpPartIteratorAdapter.java   
/**
 * Determine if given request is multipart.
 */
public static boolean isMultipart(final HttpServletRequest httpRequest) {
  // We're circumventing ServletFileUpload.isMultipartContent as some clients (nuget) use PUT for multipart uploads
  return FileUploadBase.isMultipartContent(new ServletRequestContext(httpRequest));
}
项目:subetha    文件:FileUploadFilter.java   
/**
 * Filter the current request. If it is a multipart request, parse it and
 * wrap it before chaining to the next filter or servlet. Otherwise, pass
 * it on untouched.
 */
@Override
@SuppressWarnings("unchecked")
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
    throws IOException, ServletException
{
    if (!FileUploadBase.isMultipartContent(request))
    {
        chain.doFilter(request, response);
        return;
    }

    try
    {
        //FileItemFactory fact = new DiskFileItemFactory();
        //FileUpload upload = new ServletFileUpload(fact);
        DiskFileUpload upload = new DiskFileUpload();
        upload.setSizeMax(MAX_UPLOAD_BYTES);

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

        Map<String, String[]> params = new HashMap<String, String[]>();
        List<FileItem> files = new ArrayList<FileItem>(items.size());

        for (FileItem item: items)
        {
            if (item.isFormField())
            {
                // Add it to the array in the params, creating the array if necessary
                String[] array = params.get(item.getFieldName());
                if (array == null)
                {
                    array = new String[] { item.getString() };
                }
                else
                {
                    String[] newArray = new String[array.length + 1];
                    System.arraycopy(array, 0, newArray, 0, array.length);
                    newArray[newArray.length - 1] = item.getString();

                    array = newArray;
                }

                params.put(item.getFieldName(), array);
            }
            else
                files.add(item);
        }

        request.setAttribute(ATTR_FILES, files);
        HttpServletRequest wrapped = new RequestWrapper(request, params);

        chain.doFilter(wrapped, response);
    }
    catch (FileUploadException ex)
    {
        // Just save the exception for later.
        request.setAttribute(ATTR_EXCEPTION, ex);

        chain.doFilter(request, response);
    }
}
项目:ProteanBear_Java    文件:FileUploader.java   
/**
 * 执行上传
 *
 * @param request  : {@link HttpServletRequest} 对象
 * @param response : {@link HttpServletResponse} 对象
 */
public Result upload(HttpServletRequest request,
                     HttpServletResponse response)
{
    reset();

    String absolutePath=getAbsoluteSavePath(request);
    if(absolutePath==null)
    {
        cause=new FileNotFoundException(String.format("path '%s' not found or is not directory",savePath));
        return Result.INVALID_SAVE_PATH;
    }

    ServletFileUpload sfu=getFileUploadComponent();
    List<FileItemInfo> fiis=new ArrayList<>();

    List<FileItem> items=null;
    Result result=Result.SUCCESS;

    String encoding=servletHeaderencoding!=null?servletHeaderencoding:request.getCharacterEncoding();
    FileNameGenerator fnGenerator=fileNameGenerator!=null?fileNameGenerator:DEFAULT_FILE_NAME_GENERATOR;

    try
    {
        items=(List<FileItem>)sfu.parseRequest(request);
    }
    catch(FileUploadException e)
    {
        cause=e;

        if(e instanceof FileUploadBase.FileSizeLimitExceededException)
        {
            result=Result.FILE_SIZE_EXCEEDED;
        }
        else if(e instanceof FileUploadBase.SizeLimitExceededException)
        {
            result=Result.SIZE_EXCEEDED;
        }
        else if(e instanceof FileUploadBase.InvalidContentTypeException)
        {
            result=Result.INVALID_CONTENT_TYPE;
        }
        else if(e instanceof FileUploadBase.IOFileUploadException)
        {
            result=Result.FILE_UPLOAD_IO_EXCEPTION;
        }
        else
        {
            result=Result.OTHER_PARSE_REQUEST_EXCEPTION;
        }
    }

    if(result==Result.SUCCESS)
    {
        result=parseFileItems(items,fnGenerator,absolutePath,encoding,fiis);
        if(result==Result.SUCCESS)
        {
            result=writeFiles(fiis);
        }
    }

    return result;
}
项目:WidgetStore    文件:ServletFileUpload.java   
/**
 * Utility method that determines whether the request contains multipart
 * content.
 *
 * @param request The servlet request to be evaluated. Must be non-null.
 *
 * @return <code>true</code> if the request is multipart;
 *         <code>false</code> otherwise.
 */
public static final boolean isMultipartContent(
        HttpServletRequest request) {
    if (!POST_METHOD.equalsIgnoreCase(request.getMethod())) {
        return false;
    }
    return FileUploadBase.isMultipartContent(new ServletRequestContext(request));
}
项目:WidgetStore    文件:PortletFileUpload.java   
/**
 * Utility method that determines whether the request contains multipart
 * content.
 *
 * @param request The portlet request to be evaluated. Must be non-null.
 *
 * @return <code>true</code> if the request is multipart;
 *         <code>false</code> otherwise.
 */
public static final boolean isMultipartContent(ActionRequest request) {
    return FileUploadBase.isMultipartContent(
            new PortletRequestContext(request));
}