Java Code Examples for org.apache.commons.fileupload.FileItemStream

The following examples show how to use org.apache.commons.fileupload.FileItemStream. 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: dcs-sdk-java   Source File: MultipartStreamCopy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the next byte in the stream.
 *
 * @return The next byte in the stream, as a non-negative
 * integer, or -1 for EOF.
 * @throws IOException An I/O error occurred.
 */
@Override
public int read() throws IOException {
    if (closed) {
        throw new FileItemStream.ItemSkippedException();
    }
    if (available() == 0 && makeAvailable() == 0) {
        return -1;
    }
    ++total;
    int b = buffer[head++];
    if (b >= 0) {
        return b;
    }
    return b + BYTE_POSITIVE_OFFSET;
}
 
Example 2
Source Project: dcs-sdk-java   Source File: MultipartStreamCopy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads bytes into the given buffer.
 *
 * @param b   The destination buffer, where to write to.
 * @param off Offset of the first byte in the buffer.
 * @param len Maximum number of bytes to read.
 * @return Number of bytes, which have been actually read,
 * or -1 for EOF.
 * @throws IOException An I/O error occurred.
 */
@Override
public int read(byte[] b, int off, int len) throws IOException {
    if (closed) {
        throw new FileItemStream.ItemSkippedException();
    }
    if (len == 0) {
        return 0;
    }
    int res = available();
    if (res == 0) {
        res = makeAvailable();
        if (res == 0) {
            return -1;
        }
    }
    res = Math.min(res, len);
    System.arraycopy(buffer, head, b, off, res);
    head += res;
    total += res;
    return res;
}
 
Example 3
Source Project: dcs-sdk-java   Source File: MultipartStreamCopy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Skips the given number of bytes.
 *
 * @param bytes Number of bytes to skip.
 * @return The number of bytes, which have actually been
 * skipped.
 * @throws IOException An I/O error occurred.
 */
@Override
public long skip(long bytes) throws IOException {
    if (closed) {
        throw new FileItemStream.ItemSkippedException();
    }
    int av = available();
    if (av == 0) {
        av = makeAvailable();
        if (av == 0) {
            return 0;
        }
    }
    long res = Math.min(av, bytes);
    head += res;
    return res;
}
 
Example 4
Source Project: multiapps-controller   Source File: FilesApiServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private List<FileEntry> uploadFiles(HttpServletRequest request, String spaceGuid, String namespace)
    throws FileUploadException, IOException, FileStorageException {
    List<FileEntry> uploadedFiles = new ArrayList<>();
    FileItemIterator fileItemIterator = createFileIterator(request);

    while (fileItemIterator.hasNext()) {
        FileItemStream item = fileItemIterator.next();
        if (item.isFormField()) {
            continue; // ignore simple (non-file) form fields
        }

        try (InputStream in = item.openStream()) {
            FileEntry entry = fileService.addFile(spaceGuid, namespace, item.getName(), in);
            uploadedFiles.add(entry);
        }
    }
    return uploadedFiles;
}
 
Example 5
private Map<String, String> getMultipartParameterMap()
		throws RepositoryException, IOException, FileUploadException {
	Map<String, String> parameters = new HashMap<>();
	ServletFileUpload upload = new ServletFileUpload();
	FileItemIterator iter = upload.getItemIterator(this);
	while (iter.hasNext()) {
		FileItemStream item = iter.next();
		String name = item.getFieldName();
		if ("content".equals(name)) {
			content = item.openStream();
			contentFileName = item.getName();
			break;
		} else {
			parameters.put(name, firstLine(item));
		}
	}
	return parameters;
}
 
Example 6
Source Project: nio-multipart   Source File: MultipartController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p> Example of parsing the multipart request using commons file upload. In this case the parsing happens in blocking io.
 *
 * @param request The {@code HttpServletRequest}
 * @return The {@code VerificationItems}
 * @throws Exception if an exception happens during the parsing
 */
@RequestMapping(value = "/blockingio/fileupload/multipart", method = RequestMethod.POST)
public @ResponseBody VerificationItems blockingIoMultipart(final HttpServletRequest request) throws Exception {

    assertRequestIsMultipart(request);

    final ServletFileUpload servletFileUpload = new ServletFileUpload();
    final FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);

    final VerificationItems verificationItems = new VerificationItems();
    Metadata metadata = null;
    while (fileItemIterator.hasNext()){
        FileItemStream fileItemStream = fileItemIterator.next();
        if (METADATA_FIELD_NAME.equals(fileItemStream.getFieldName())){
            if (metadata != null){
                throw new IllegalStateException("Found more than one metadata field");
            }
            metadata = unmarshalMetadata(fileItemStream.openStream());
        }else {
            VerificationItem verificationItem = buildVerificationItem(fileItemStream.openStream(), fileItemStream.getFieldName(), fileItemStream.isFormField());
            verificationItems.getVerificationItems().add(verificationItem);
        }
    }
    processVerificationItems(verificationItems, metadata, false, request.getHeader(VERIFICATION_CONTROL_HEADER_NAME));
    return verificationItems;
}
 
Example 7
Source Project: nio-multipart   Source File: FunctionalTest.java    License: Apache License 2.0 6 votes vote down vote up
void dumpFileIterator(final FileItemIterator fileItemIterator){

        int partIndex = 0;

        try {
            log.info("-- COMMONS FILE UPLOAD --");
            while (fileItemIterator.hasNext()) {
                log.info("-- Part " + partIndex++);
                FileItemStream fileItemStream = fileItemIterator.next();

                FileItemHeaders fileItemHeaders = fileItemStream.getHeaders();
                Iterator<String> headerNames = fileItemHeaders.getHeaderNames();
                while(headerNames.hasNext()){
                    String headerName = headerNames.next();
                    log.info("Header: " + headerName+ ": " + Joiner.on(',').join(fileItemHeaders.getHeaders(headerName)));
                }
                log.info("Body:\n" + IOUtils.toString(fileItemStream.openStream()));
            }
            log.info("-- ------------------- --");
        }catch (Exception e){
            log.error("Error dumping the FileItemIterator", e);
        }

    }
 
Example 8
Source Project: getting-started-java   Source File: CloudStorageHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME environment
 * variable, appending a timestamp to end of the uploaded filename.
 */
public String uploadFile(FileItemStream fileStream, final String bucketName)
    throws IOException, ServletException {
  checkFileExtension(fileStream.getName());

  System.out.println("FileStream name: " + fileStream.getName() + "\nBucket name: " + bucketName);

  DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  String dtString = dt.toString(dtf);
  final String fileName = fileStream.getName() + dtString;

  // the inputstream is closed by default, so we don't need to close it here
  @SuppressWarnings("deprecation")
  BlobInfo blobInfo =
      storage.create(
          BlobInfo.newBuilder(bucketName, fileName)
              // Modify access list to allow all users with link to read file
              .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
              .build(),
          fileStream.openStream());
  logger.log(
      Level.INFO, "Uploaded file {0} as {1}", new Object[] {fileStream.getName(), fileName});
  // return the public download link
  return blobInfo.getMediaLink();
}
 
Example 9
Source Project: getting-started-java   Source File: CloudStorageHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
 * environment variable, appending a timestamp to end of the uploaded filename.
 */
public String uploadFile(FileItemStream fileStream, final String bucketName)
    throws IOException, ServletException {
  checkFileExtension(fileStream.getName());

  DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  String dtString = dt.toString(dtf);
  final String fileName = fileStream.getName() + dtString;

  // the inputstream is closed by default, so we don't need to close it here
  @SuppressWarnings("deprecation")
  BlobInfo blobInfo =
      storage.create(
          BlobInfo
              .newBuilder(bucketName, fileName)
              // Modify access list to allow all users with link to read file
              .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
              .build(),
          fileStream.openStream());
  logger.log(Level.INFO, "Uploaded file {0} as {1}", new Object[]{
      fileStream.getName(), fileName});
  // return the public download link
  return blobInfo.getMediaLink();
}
 
Example 10
Source Project: getting-started-java   Source File: CloudStorageHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
 * environment variable, appending a timestamp to end of the uploaded filename.
 */
@SuppressWarnings("deprecation")
public String uploadFile(FileItemStream fileStream, final String bucketName)
    throws IOException, ServletException {
  checkFileExtension(fileStream.getName());

  DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  String dtString = dt.toString(dtf);
  final String fileName = fileStream.getName() + dtString;

  // the inputstream is closed by default, so we don't need to close it here
  BlobInfo blobInfo =
      storage.create(
          BlobInfo
              .newBuilder(bucketName, fileName)
              // Modify access list to allow all users with link to read file
              .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
              .build(),
          fileStream.openStream());
  // return the public download link
  return blobInfo.getMediaLink();
}
 
Example 11
Source Project: getting-started-java   Source File: CloudStorageHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
 * environment variable, appending a timestamp to end of the uploaded filename.
 */
public String uploadFile(FileItemStream fileStream, final String bucketName)
    throws IOException, ServletException {
  checkFileExtension(fileStream.getName());

  DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  String dtString = dt.toString(dtf);
  final String fileName = fileStream.getName() + dtString;

  // the inputstream is closed by default, so we don't need to close it here
  @SuppressWarnings("deprecation")
  BlobInfo blobInfo =
      storage.create(
          BlobInfo
              .newBuilder(bucketName, fileName)
              // Modify access list to allow all users with link to read file
              .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
              .build(),
          fileStream.openStream());
  // return the public download link
  return blobInfo.getMediaLink();
}
 
Example 12
Source Project: flow   Source File: StreamReceiverHandler.java    License: Apache License 2.0 6 votes vote down vote up
private boolean handleMultipartFileUploadFromInputStream(VaadinSession session,
        VaadinRequest request, StreamReceiver streamReceiver,
        StateNode owner) throws IOException {
    boolean success = true;
    long contentLength = request.getContentLength();
    // Parse the request
    FileItemIterator iter;
    try {
        iter = getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            boolean itemSuccess = handleStream(session, streamReceiver,
                    owner, contentLength, item);
            success = success && itemSuccess;
        }
    } catch (FileUploadException e) {
        success = false;
        getLogger().warn("File upload failed.", e);
    }
    return success;
}
 
Example 13
Source Project: RestServices   Source File: MicroflowService.java    License: Apache License 2.0 6 votes vote down vote up
private void parseMultipartData(RestServiceRequest rsr, IMendixObject argO,
		JSONObject data) throws IOException, FileUploadException {
	boolean hasFile = false;
	
	for(FileItemIterator iter = servletFileUpload.getItemIterator(rsr.request); iter.hasNext();) {
		FileItemStream item = iter.next();
		if (!item.isFormField()){ //This is the file(?!)
			if (!isFileSource) {
				RestServices.LOGPUBLISH.warn("Received request with binary data but input argument isn't a filedocument. Skipping. At: " + rsr.request.getRequestURL().toString());
				continue;
			}
			if (hasFile)
				RestServices.LOGPUBLISH.warn("Received request with multiple files. Only one is supported. At: " + rsr.request.getRequestURL().toString());
			hasFile = true;
			Core.storeFileDocumentContent(rsr.getContext(), argO, determineFileName(item), item.openStream());
		}
		else
			data.put(item.getFieldName(), IOUtils.toString(item.openStream()));
	}
}
 
Example 14
Source Project: actframework   Source File: MultipartStream.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the next byte in the stream.
 * @return The next byte in the stream, as a non-negative
 *   integer, or -1 for EOF.
 * @throws IOException An I/O error occurred.
 */
public int read() throws IOException {
    if (closed) {
        throw new FileItemStream.ItemSkippedException();
    }
    if (available() == 0) {
        if (makeAvailable() == 0) {
            return -1;
        }
    }
    ++total;
    int b = buffer[head++];
    if (b >= 0) {
        return b;
    }
    return b + BYTE_POSITIVE_OFFSET;
}
 
Example 15
Source Project: actframework   Source File: MultipartStream.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads bytes into the given buffer.
 * @param b The destination buffer, where to write to.
 * @param off Offset of the first byte in the buffer.
 * @param len Maximum number of bytes to read.
 * @return Number of bytes, which have been actually read,
 *   or -1 for EOF.
 * @throws IOException An I/O error occurred.
 */
public int read(byte[] b, int off, int len) throws IOException {
    if (closed) {
        throw new FileItemStream.ItemSkippedException();
    }
    if (len == 0) {
        return 0;
    }
    int res = available();
    if (res == 0) {
        res = makeAvailable();
        if (res == 0) {
            return -1;
        }
    }
    res = Math.min(res, len);
    System.arraycopy(buffer, head, b, off, res);
    head += res;
    total += res;
    return res;
}
 
Example 16
Source Project: actframework   Source File: MultipartStream.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Skips the given number of bytes.
 * @param bytes Number of bytes to skip.
 * @return The number of bytes, which have actually been
 *   skipped.
 * @throws IOException An I/O error occurred.
 */
public long skip(long bytes) throws IOException {
    if (closed) {
        throw new FileItemStream.ItemSkippedException();
    }
    int av = available();
    if (av == 0) {
        av = makeAvailable();
        if (av == 0) {
            return 0;
        }
    }
    long res = Math.min(av, bytes);
    head += res;
    return res;
}
 
Example 17
Source Project: restcommander   Source File: MultipartStream.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the next byte in the stream.
 * @return The next byte in the stream, as a non-negative
 *   integer, or -1 for EOF.
 * @throws IOException An I/O error occurred.
 */
public int read() throws IOException {
    if (closed) {
        throw new FileItemStream.ItemSkippedException();
    }
    if (available() == 0) {
        if (makeAvailable() == 0) {
            return -1;
        }
    }
    ++total;
    int b = buffer[head++];
    if (b >= 0) {
        return b;
    }
    return b + BYTE_POSITIVE_OFFSET;
}
 
Example 18
Source Project: restcommander   Source File: MultipartStream.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads bytes into the given buffer.
 * @param b The destination buffer, where to write to.
 * @param off Offset of the first byte in the buffer.
 * @param len Maximum number of bytes to read.
 * @return Number of bytes, which have been actually read,
 *   or -1 for EOF.
 * @throws IOException An I/O error occurred.
 */
public int read(byte[] b, int off, int len) throws IOException {
    if (closed) {
        throw new FileItemStream.ItemSkippedException();
    }
    if (len == 0) {
        return 0;
    }
    int res = available();
    if (res == 0) {
        res = makeAvailable();
        if (res == 0) {
            return -1;
        }
    }
    res = Math.min(res, len);
    System.arraycopy(buffer, head, b, off, res);
    head += res;
    total += res;
    return res;
}
 
Example 19
Source Project: restcommander   Source File: MultipartStream.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Skips the given number of bytes.
 * @param bytes Number of bytes to skip.
 * @return The number of bytes, which have actually been
 *   skipped.
 * @throws IOException An I/O error occurred.
 */
public long skip(long bytes) throws IOException {
    if (closed) {
        throw new FileItemStream.ItemSkippedException();
    }
    int av = available();
    if (av == 0) {
        av = makeAvailable();
        if (av == 0) {
            return 0;
        }
    }
    long res = Math.min(av, bytes);
    head += res;
    return res;
}
 
Example 20
Source Project: jeewx-boot   Source File: OSSBootUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(FileItemStream file, String fileDir) {
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    try {
        String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);

        if (oConvertUtils.isNotEmpty(imgDomain)) {
            FILE_URL = imgDomain + "/"  + fileUrl;
        } else {
            FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
        }

        PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        if (result != null) {
            System.out.println("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
 
Example 21
Source Project: jeecg-cloud   Source File: OssBootUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(FileItemStream file, String fileDir) {
    String FILE_URL = null;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    try {
        String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);

        if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
            FILE_URL = staticDomain + "/" + fileUrl;
        } else {
            FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
        }
        PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        if (result != null) {
            log.info("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
 
Example 22
Source Project: s2g-zuul   Source File: FilterScriptManagerServlet.java    License: MIT License 5 votes vote down vote up
private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        org.apache.commons.fileupload.FileItemIterator it = null;
        try {
            it = upload.getItemIterator(request);

            while (it.hasNext()) {
                FileItemStream stream = it.next();
                InputStream input = stream.openStream();

                // NOTE: we are going to pull the entire stream into memory
                // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger
                byte[] uploadedBytes = getBytesFromInputStream(input);
                input.close();

                if (uploadedBytes.length == 0) {
                    setUsageError(400, "ERROR: Body contained no data.", response);
                    return null;
                }

                return new String(uploadedBytes);
            }
        } catch (FileUploadException e) {
            throw new IOException(e.getMessage());
        }
        return null;
    }
 
Example 23
Source Project: appinventor-extensions   Source File: GalleryServlet.java    License: Apache License 2.0 5 votes vote down vote up
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName)
      throws Exception {
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iterator = upload.getItemIterator(req);
    while (iterator.hasNext()) {
      FileItemStream item = iterator.next();
//      LOG.info(item.getContentType());
      if (item.getFieldName().equals(expectedFieldName)) {
        return item.openStream();
      }
    }
    throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload");
  }
 
Example 24
Source Project: appinventor-extensions   Source File: UploadServlet.java    License: Apache License 2.0 5 votes vote down vote up
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName)
    throws Exception {
  ServletFileUpload upload = new ServletFileUpload();
  FileItemIterator iterator = upload.getItemIterator(req);
  while (iterator.hasNext()) {
    FileItemStream item = iterator.next();
    if (item.getFieldName().equals(expectedFieldName)) {
      return item.openStream();
    }
  }

  throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload");
}
 
Example 25
Source Project: httplite   Source File: MiscHandle.java    License: Apache License 2.0 5 votes vote down vote up
private String handleMultipart(RecordedRequest request) {
    RecordedUpload upload = new RecordedUpload(request);
    Exception exception;
    try {
        Map<String,String> params = new HashMap<>();
        FileItemIterator iter = upload.getItemIterator();
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(stream);
                System.out.println("Form field " + name + " with value "
                        + value + " detected.");
                params.put(name,value);
            } else {
                System.out.println("File field " + name + " with file name "
                        + item.getName() + " detected.");
                params.put(name, "file->"+item.getName());
            }
        }
        return "Multipart:"+JSON.toJSONString(params);
    } catch (Exception e) {
        exception = e;
    }
    return "Multipart:error->"+exception;
}
 
Example 26
Source Project: nio-multipart   Source File: FunctionalTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void blockingIOAdapterFunctionalTest() throws Exception {

    log.info("BLOCKING IO ADAPTER FUNCTIONAL TEST [ " + testCase.getDescription() + " ]");

    if (log.isDebugEnabled()){
        log.debug("Request body\n" + IOUtils.toString(testCase.getBodyInputStream()));
    }

    final FileUpload fileUpload = new FileUpload();
    final FileItemIterator fileItemIterator = fileUpload.getItemIterator(testCase.getRequestContext());

    try(final CloseableIterator<ParserToken> parts = Multipart.multipart(testCase.getMultipartContext()).forBlockingIO(testCase.getBodyInputStream())) {

        while (parts.hasNext()) {

            ParserToken parserToken = parts.next();
            ParserToken.Type partItemType = parserToken.getType();
            if (ParserToken.Type.NESTED_END.equals(partItemType) || ParserToken.Type.NESTED_START.equals(partItemType)) {
                // Commons file upload is not returning an item representing the start/end of a nested multipart.
                continue;
            }
            assertTrue(fileItemIterator.hasNext());
            FileItemStream fileItemStream = fileItemIterator.next();
            assertEquals(parserToken, fileItemStream);
        }
    }

}
 
Example 27
Source Project: nio-multipart   Source File: FunctionalTest.java    License: Apache License 2.0 5 votes vote down vote up
static void assertEquals(final ParserToken parserToken, final FileItemStream fileItemStream) throws IOException {

        if (parserToken instanceof BlockingIOAdapter.Part){
            BlockingIOAdapter.Part part = (BlockingIOAdapter.Part) parserToken;
            assertHeadersAreEqual(fileItemStream.getHeaders(), part.getHeaders());
            assertInputStreamsAreEqual(part.getPartBody(), fileItemStream.openStream());
        }else{
            fail("Invalid part item type " + parserToken.getClass());
        }

    }
 
Example 28
Source Project: nexus-public   Source File: ExtDirectServlet.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private String getTransactionId(final FileItemIterator fileItems)
    throws org.apache.commons.fileupload.FileUploadException, IOException
{
  String tid = null;
  while (tid == null && fileItems.hasNext()) {
    FileItemStream fileItemStream = fileItems.next();
    if (StringUtils.equals(fileItemStream.getFieldName(), FormPostRequestData.TID_ELEMENT)) {
      StringWriter writer = new StringWriter();
      IOUtils.copy(fileItemStream.openStream(), writer, UTF_8);
      tid = writer.toString();
    }
  }
  return tid;
}
 
Example 29
Source Project: jeewx   Source File: Uploader.java    License: Apache License 2.0 5 votes vote down vote up
private void parseParams() {

		DiskFileItemFactory dff = new DiskFileItemFactory();
		try {
			ServletFileUpload sfu = new ServletFileUpload(dff);
			sfu.setSizeMax(this.maxSize);
			sfu.setHeaderEncoding(Uploader.ENCODEING);

			FileItemIterator fii = sfu.getItemIterator(this.request);

			while (fii.hasNext()) {
				FileItemStream item = fii.next();
				// 普通参数存储
				if (item.isFormField()) {

					this.params.put(item.getFieldName(),
							this.getParameterValue(item.openStream()));

				} else {

					// 只保留一个
					if (this.inputStream == null) {
						this.inputStream = item.openStream();
						this.originalName = item.getName();
						return;
					}

				}

			}

		} catch (Exception e) {
			this.state = this.errorInfo.get("UNKNOWN");
		}

	}
 
Example 30
Source Project: flow   Source File: StreamReceiverHandler.java    License: Apache License 2.0 5 votes vote down vote up
private boolean handleStream(VaadinSession session,
        StreamReceiver streamReceiver, StateNode owner, long contentLength,
        FileItemStream item) throws IOException {
    String name = item.getName();
    InputStream stream = item.openStream();
    try {
        return handleFileUploadValidationAndData(session, stream,
                streamReceiver, name, item.getContentType(), contentLength,
                owner);
    } catch (UploadException e) {
        session.getErrorHandler().error(new ErrorEvent(e));
    }
    return false;
}