Java Code Examples for org.apache.commons.fileupload.servlet.ServletRequestContext

The following examples show how to use org.apache.commons.fileupload.servlet.ServletRequestContext. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: mumu   Source File: UploadUtil.java    License: Apache License 2.0 6 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 2
Source Project: carbon-identity-framework   Source File: SecurityUIUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static List parseRequest(ServletRequestContext requestContext)
        throws FileUploadException {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    return upload.parseRequest(requestContext);
}
 
Example 3
Source Project: attic-stratos   Source File: AbstractFileUploadExecutor.java    License: Apache License 2.0 5 votes vote down vote up
protected List parseRequest(ServletRequestContext requestContext) throws FileUploadException {
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    return upload.parseRequest(requestContext);
}
 
Example 4
Source Project: attic-stratos   Source File: AbstractFileUploadExecutor.java    License: Apache License 2.0 5 votes vote down vote up
protected File uploadFile(HttpServletRequest request,
                          String repoDir,
                          HttpServletResponse response,
                          String extension) throws FileUploadException {

    response.setContentType("text/html; charset=utf-8");
    ServletRequestContext servletRequestContext = new ServletRequestContext(request);
    boolean isMultipart =
            ServletFileUpload.isMultipartContent(servletRequestContext);
    File uploadedFile = null;
    if (isMultipart) {
        try {
            // Create a new file upload handler
            List items = parseRequest(servletRequestContext);

            // Process the uploaded items
            for (Iterator iter = items.iterator(); iter.hasNext();) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String fileExtension = fileName;
                    fileExtension = fileExtension.toLowerCase();
                    if (extension != null && !fileExtension.endsWith(extension)) {
                        throw new Exception(" Illegal file type. Only " +
                                            extension + " files can be uploaded");

                    }
                    String fileNameOnly = getFileName(fileName);
                    uploadedFile = new File(repoDir, fileNameOnly);
                    item.write(uploadedFile);
                }
            }
        } catch (Exception e) {
            String msg = "File upload failed";
            log.error(msg, e);
            throw new FileUploadException(msg, e);
        }
    }
    return uploadedFile;
}
 
Example 5
Source Project: Brutusin-RPC   Source File: RpcServlet.java    License: Apache License 2.0 4 votes vote down vote up
/**
 *
 * @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;
}
 
Example 6
/**
 * @param requestContext
 * @return
 * @throws FileUploadException
 */
private List parseRequest(ServletRequestContext requestContext) throws FileUploadException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    return upload.parseRequest(requestContext);
}
 
Example 7
/**
 * 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));
}
 
Example 8
/**
 * @param requestContext
 * @return
 * @throws FileUploadException
 */
private List parseRequest(ServletRequestContext requestContext) throws FileUploadException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    return upload.parseRequest(requestContext);
}
 
Example 9
Source Project: carbon-identity   Source File: SecurityUIUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static List parseRequest(ServletRequestContext requestContext)
        throws FileUploadException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    return upload.parseRequest(requestContext);
}
 
Example 10
Source Project: attic-stratos   Source File: AbstractFileUploadExecutor.java    License: Apache License 2.0 4 votes vote down vote up
protected void parseRequest(HttpServletRequest request) throws FileUploadFailedException,
                                                             FileSizeLimitExceededException {
    fileItemsMap.set(new HashMap<String, ArrayList<FileItemData>>());
    formFieldsMap.set(new HashMap<String, ArrayList<String>>());

    ServletRequestContext servletRequestContext = new ServletRequestContext(request);
    boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext);
    Long totalFileSize = 0L;

    if (isMultipart) {

        List items;
        try {
            items = parseRequest(servletRequestContext);
        } catch (FileUploadException e) {
            String msg = "File upload failed";
            log.error(msg, e);
            throw new FileUploadFailedException(msg, e);
        }
        boolean multiItems = false;
        if (items.size() > 1) {
            multiItems = true;
        }

        // Add the uploaded items to the corresponding maps.
        for (Iterator iter = items.iterator(); iter.hasNext();) {
            FileItem item = (FileItem) iter.next();
            String fieldName = item.getFieldName().trim();
            if (item.isFormField()) {
                if (formFieldsMap.get().get(fieldName) == null) {
                    formFieldsMap.get().put(fieldName, new ArrayList<String>());
                }
                try {
                    formFieldsMap.get().get(fieldName).add(new String(item.get(), "UTF-8"));
                } catch (UnsupportedEncodingException ignore) {
                }
            } else {
                String fileName = item.getName();
                if ((fileName == null || fileName.length() == 0) && multiItems) {
                    continue;
                }
                if (fileItemsMap.get().get(fieldName) == null) {
                    fileItemsMap.get().put(fieldName, new ArrayList<FileItemData>());
                }
                totalFileSize += item.getSize();
                if (totalFileSize < totalFileUploadSizeLimit) {
                    fileItemsMap.get().get(fieldName).add(new FileItemData(item));
                } else {
                    throw new FileSizeLimitExceededException(getFileSizeLimit() / 1024 / 1024);
                }
            }
        }
    }
}
 
Example 11
Source Project: steady   Source File: FileUploadBase.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
 * compliant <code>multipart/form-data</code> stream.
 *
 * @param req The servlet request to be parsed.
 *
 * @return A list of <code>FileItem</code> instances parsed from the
 *         request, in the order that they were transmitted.
 *
 * @throws FileUploadException if there are problems reading/parsing
 *                             the request or storing files.
 *
 * @deprecated 1.1 Use {@link ServletFileUpload#parseRequest(HttpServletRequest)} instead.
 */
@Deprecated
public List<FileItem> parseRequest(HttpServletRequest req)
throws FileUploadException {
    return parseRequest(new ServletRequestContext(req));
}
 
Example 12
Source Project: lams   Source File: FileUploadBase.java    License: GNU General Public License v2.0 2 votes vote down vote up
/**
 * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
 * compliant <code>multipart/form-data</code> stream.
 *
 * @param req The servlet request to be parsed.
 *
 * @return A list of <code>FileItem</code> instances parsed from the
 *         request, in the order that they were transmitted.
 *
 * @throws FileUploadException if there are problems reading/parsing
 *                             the request or storing files.
 *
 * @deprecated 1.1 Use {@link ServletFileUpload#parseRequest(HttpServletRequest)} instead.
 */
@Deprecated
public List<FileItem> parseRequest(HttpServletRequest req)
throws FileUploadException {
    return parseRequest(new ServletRequestContext(req));
}