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

项目:dcs-sdk-java    文件:MultipartStreamCopy.java   
/**
 * 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;
}
项目:dcs-sdk-java    文件:MultipartStreamCopy.java   
/**
 * 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;
}
项目:dcs-sdk-java    文件:MultipartStreamCopy.java   
/**
 * 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;
}
项目:struts2    文件:JakartaStreamMultiPartRequest.java   
/**
 * Processes the FileItemStream as a Form Field.
 *
 * @param itemStream file item stream
 */
private void processFileItemStreamAsFormField(FileItemStream itemStream) {
    String fieldName = itemStream.getFieldName();
    try {
        List<String> values;
        String fieldValue = Streams.asString(itemStream.openStream());
        if (!parameters.containsKey(fieldName)) {
            values = new ArrayList<>();
            parameters.put(fieldName, values);
        } else {
            values = parameters.get(fieldName);
        }
        values.add(fieldValue);
    } catch (IOException e) {
        LOG.warn("Failed to handle form field '{}'.", fieldName, e);
    }
}
项目:struts2    文件:JakartaStreamMultiPartRequest.java   
/**
 * Processes the FileItemStream as a file field.
 *
 * @param itemStream file item stream
 * @param location location
 */
private void processFileItemStreamAsFileField(FileItemStream itemStream, String location) {
    // Skip file uploads that don't have a file name - meaning that no file was selected.
    if (itemStream.getName() == null || itemStream.getName().trim().length() < 1) {
        LOG.debug("No file has been uploaded for the field: {}", itemStream.getFieldName());
        return;
    }

    File file = null;
    try {
        // Create the temporary upload file.
        file = createTemporaryFile(itemStream.getName(), location);

        if (streamFileToDisk(itemStream, file)) {
            createFileInfoFromItemStream(itemStream, file);
        }
    } catch (IOException e) {
        if (file != null) {
            try {
                file.delete();
            } catch (SecurityException se) {
                LOG.warn("Failed to delete '{}' due to security exception above.", file.getName(), se);
            }
        }
    }
}
项目:struts2    文件:JakartaStreamMultiPartRequest.java   
/**
 * Creates an internal <code>FileInfo</code> structure used to pass information
 * to the <code>FileUploadInterceptor</code> during the interceptor stack
 * invocation process.
 *
 * @param itemStream file item stream
 * @param file the file
 */
private void createFileInfoFromItemStream(FileItemStream itemStream, File file) {
    // gather attributes from file upload stream.
    String fileName = itemStream.getName();
    String fieldName = itemStream.getFieldName();
    // create internal structure
    FileInfo fileInfo = new FileInfo(file, itemStream.getContentType(), fileName);
    // append or create new entry.
    if (!fileInfos.containsKey(fieldName)) {
        List<FileInfo> infos = new ArrayList<>();
        infos.add(fileInfo);
        fileInfos.put(fieldName, infos);
    } else {
        fileInfos.get(fieldName).add(fileInfo);
    }
}
项目:aet    文件:SuiteServlet.java   
private Map<String, String> getRequestData(HttpServletRequest request) {
  Map<String, String> requestData = new HashMap<>();

  ServletFileUpload upload = new ServletFileUpload();
  try {
    FileItemIterator itemIterator = upload.getItemIterator(request);
    while (itemIterator.hasNext()) {
      FileItemStream item = itemIterator.next();
      InputStream itemStream = item.openStream();
      String value = Streams.asString(itemStream, CharEncoding.UTF_8);
      requestData.put(item.getFieldName(), value);
    }
  } catch (FileUploadException | IOException e) {
    LOGGER.error("Failed to process request", e);
  }

  return requestData;
}
项目:nio-multipart    文件:MultipartController.java   
/**
 * <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;
}
项目:nio-multipart    文件:FunctionalTest.java   
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);
        }

    }
项目:getting-started-java    文件:CloudStorageHelper.java   
/**
 * 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();
}
项目:getting-started-java    文件:CloudStorageHelper.java   
/**
 * 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();
}
项目:getting-started-java    文件:CloudStorageHelper.java   
/**
 * 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();
}
项目:jeecms6    文件:SnapScreenServlet.java   
private InputStream getInputStreamFromRequest(HttpServletRequest request) {
    InputStream inputStream=null;
    DiskFileItemFactory dff = new DiskFileItemFactory();
    try {
        ServletFileUpload sfu = new ServletFileUpload(dff);
        FileItemIterator fii = sfu.getItemIterator(request);
        while (fii.hasNext()) {
            FileItemStream item = fii.next();
            // 普通参数存储
            if (!item.isFormField()) {
                // 只保留一个
                if (inputStream == null) {
                    inputStream = item.openStream();
                    return inputStream;
                }
            } 
        }
    } catch (Exception e) {
    }
    return inputStream;
}
项目:geowe-core    文件:FileUploadZipServlet.java   
private ZipFile createZipFile(FileItemStream item) {
    ZipFile zipFile = null;
    try {
        File f = new File("zipFile");
        InputStream inputStream = item.openStream();
        OutputStream outputStream = new FileOutputStream(f);
        int len;
        byte[] buffer = new byte[1000000];
        while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();

        zipFile = new ZipFile(f);

    } catch (Exception e) {
        LOG.error(e.getMessage());
    }

    return zipFile;
}
项目:elfinder-java-connector    文件:UploadCommand.java   
@Override
protected void execute(ElfinderStorage elfinderStorage, HttpServletRequest request, JSONObject json) throws Exception {

    List<FileItemStream> files = (List<FileItemStream>) request.getAttribute(FileItemStream.class.getName());
    List<VolumeHandler> added = new ArrayList<>();

    String target = request.getParameter(ElFinderConstants.ELFINDER_PARAMETER_TARGET);
    VolumeHandler parentDir = findTarget(elfinderStorage, target);

    for (FileItemStream file : files) {
        String fileName = file.getName();
        VolumeHandler newFile = new VolumeHandler(parentDir, fileName);
        newFile.createFile();
        InputStream is = file.openStream();
        OutputStream os = newFile.openOutputStream();

        IOUtils.copy(is, os);
        os.close();
        is.close();

        added.add(newFile);
    }

    json.put(ElFinderConstants.ELFINDER_JSON_RESPONSE_ADDED, buildJsonFilesArray(request, added));
}
项目:RestServices    文件:MicroflowService.java   
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()));
    }
}
项目:actframework    文件:MultipartStream.java   
/**
 * 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;
}
项目:actframework    文件:MultipartStream.java   
/**
 * 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;
}
项目:actframework    文件:MultipartStream.java   
/**
 * 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;
}
项目:actframework    文件:UploadFileStorageService.java   
private ISObject _store(FileItemStream fileItemStream) throws IOException {
    String filename = fileItemStream.getName();
    String key = newKey(filename);
    File tmpFile = getFile(key);
    InputStream input = fileItemStream.openStream();
    ThresholdingByteArrayOutputStream output = new ThresholdingByteArrayOutputStream(inMemoryCacheThreshold, tmpFile);
    IO.copy(input, output);

    ISObject retVal;
    if (output.exceedThreshold) {
        retVal = getFull(key);
    } else {
        int size = output.written;
        byte[] buf = output.buf();
        retVal = SObject.of(key, buf, size);
    }

    if (S.notBlank(filename)) {
        retVal.setFilename(filename);
    }
    String contentType = fileItemStream.getContentType();
    if (null != contentType) {
        retVal.setContentType(contentType);
    }
    return retVal;
}
项目:domaintest    文件:EmailApiModule.java   
/**
 * Provides parsed email headers from the "headers" param in a multipart/form-data request.
 * <p>
 * Although SendGrid parses some headers for us, it doesn't parse "reply-to", so we need to do
 * this. Once we are doing it, it's easier to be consistent and use this as the sole source of
 * truth for information that originates in the headers.
 */
@Provides
@Singleton
InternetHeaders provideHeaders(FileItemIterator iterator) {
  try {
    while (iterator != null && iterator.hasNext()) {
      FileItemStream item = iterator.next();
      // SendGrid sends us the headers in the "headers" param.
      if (item.getFieldName().equals("headers")) {
        try (InputStream stream = item.openStream()) {
          // SendGrid always sends headers in UTF-8 encoding.
          return new InternetHeaders(new ByteArrayInputStream(
              CharStreams.toString(new InputStreamReader(stream, UTF_8.name())).getBytes(UTF_8)));
        }
      }
    }
  } catch (MessagingException | FileUploadException | IOException e) {
    // If we fail parsing the headers fall through returning the empty header object below.
  }
  return new InternetHeaders();  // Parsing failed or there was no "headers" param.
}
项目:sigmah    文件:MultipartRequest.java   
public void parse(MultipartRequestCallback callback) throws IOException, FileUploadException, StatusServletException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        LOGGER.error("Request content is not multipart.");
        throw new StatusServletException(Response.SC_PRECONDITION_FAILED);
    }

    final FileItemIterator iterator = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request);
    while (iterator.hasNext()) {
        // Gets the first HTTP request element.
        final FileItemStream item = iterator.next();

        if (item.isFormField()) {
            final String value = Streams.asString(item.openStream(), "UTF-8");
            properties.put(item.getFieldName(), value);

        } else if(callback != null) {
            callback.onInputStream(item.openStream(), item.getFieldName(), item.getContentType());
        }
    }
}
项目:restcommander    文件:MultipartStream.java   
/**
 * 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;
}
项目:restcommander    文件:MultipartStream.java   
/**
 * 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;
}
项目:restcommander    文件:MultipartStream.java   
/**
 * 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;
}
项目:elfinder-2.x-servlet    文件:MultipleUploadItems.java   
public void addItemProxy(final FileItemStream item) throws IOException
{
    InputStream stream = item.openStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    IOUtils.copy(stream, os);
    final byte[] bs = os.toByteArray();
    stream.close();

    addItem((FileItemStream) Proxy.newProxyInstance(this.getClass()
            .getClassLoader(), new Class[] { FileItemStream.class },
            new InvocationHandler()
            {
                @Override
                public Object invoke(Object proxy, Method method,
                        Object[] args) throws Throwable
                {
                    if ("openStream".equals(method.getName()))
                    {
                        return new ByteArrayInputStream(bs);
                    }

                    return method.invoke(item, args);
                }
            }));
}
项目:cf-mta-deploy-service    文件:FilesApiServiceImpl.java   
private List<FileEntry> uploadFiles(HttpServletRequest request, String spaceGuid)
    throws FileUploadException, IOException, FileStorageException, SLException {
    ServletFileUpload upload = getFileUploadServlet();
    long maxUploadSize = getConfiguration().getMaxUploadSize();
    upload.setSizeMax(maxUploadSize);

    List<FileEntry> uploadedFiles = new ArrayList<FileEntry>();
    FileItemIterator fileItemIterator = null;
    try {
        fileItemIterator = upload.getItemIterator(request);
    } catch (SizeLimitExceededException ex) {
        throw new SLException(MessageFormat.format(Messages.MAX_UPLOAD_SIZE_EXCEEDED, maxUploadSize));
    }
    while (fileItemIterator.hasNext()) {
        FileItemStream item = fileItemIterator.next();
        if (item.isFormField()) {
            continue; // ignore simple (non-file) form fields
        }

        InputStream in = null;
        try {
            in = item.openStream();
            FileEntry entry = getFileService().addFile(spaceGuid, item.getName(),
                getConfiguration().getFileUploadProcessor(), in);
            uploadedFiles.add(entry);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
    return uploadedFiles;
}
项目:appinventor-extensions    文件:GalleryServlet.java   
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");
  }
项目:appinventor-extensions    文件:UploadServlet.java   
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");
}
项目:full-javaee-app    文件:CustomUtilities.java   
public static String getFileType(FileItemStream file) {
    if (file != null) {
        String fileName = file.getName().toLowerCase();
        String[] splitName = fileName.split("\\.", -1);
        String lastSplit = "." + splitName[splitName.length - 1];
        return lastSplit;
    }
    return null;
}
项目:full-javaee-app    文件:CustomUtilities.java   
public static byte[] fileItemStreamToByteArray(FileItemStream item, int docType) throws IOException, FileUploadException {
    if (item != null && docType > 0) {
        byte[] array = IOUtils.toByteArray(item.openStream());
        String[] types = new String[0];
        boolean returnVal = false;

        if (docType == 1) {
            types = new String[]{".jpg", ".jpeg", ".png"};
        } else if (docType == 2) {
            types = new String[]{".pdf", ".doc", ".docx"};
        } else if (docType == 3) {
            types = new String[]{".pdf", ".jpg", ".jpeg", ".png"};
        }

        for (String type : types) {
            if (getFileType(item).contains(type)) {
                returnVal = true;
            }
        }

        if (item.getName() != null && returnVal) {
            return array;
        }


    }
    throw new InvalidFormatException();
}
项目:Brutusin-RPC    文件:RpcServlet.java   
/**
 *
 * @param req
 * @return
 * @throws IOException
 */
private static Map<String, String[]> parseMultipartParameters(HttpServletRequest req) throws IOException {
    if (isMultipartContent(req)) {
        Map<String, String[]> multipartParameters = new HashMap();
        Map<String, List<String>> map = new HashMap();
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(req);
            req.setAttribute(REQ_ATT_MULTIPART_ITERATOR, iter);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item);
                    break;
                }
                List<String> list = map.get(item.getFieldName());
                if (list == null) {
                    list = new ArrayList();
                    map.put(item.getFieldName(), list);
                }
                String encoding = req.getCharacterEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }
                list.add(Miscellaneous.toString(item.openStream(), encoding));
            }
        } catch (FileUploadException ex) {
            throw new RuntimeException(ex);
        }
        for (Map.Entry<String, List<String>> entrySet : map.entrySet()) {
            String key = entrySet.getKey();
            List<String> value = entrySet.getValue();
            multipartParameters.put(key, value.toArray(new String[value.size()]));
        }
        return multipartParameters;
    }
    return null;
}
项目:struts2    文件:JakartaStreamMultiPartRequest.java   
/**
 * Streams the file upload stream to the specified file.
 *
 * @param itemStream file item stream
 * @param file the file
 * @return true if stream was successfully
 * @throws IOException in case of IO errors
 */
private boolean streamFileToDisk(FileItemStream itemStream, File file) throws IOException {
    boolean result = false;
    try (InputStream input = itemStream.openStream();
            OutputStream output = new BufferedOutputStream(new FileOutputStream(file), bufferSize)) {
        byte[] buffer = new byte[bufferSize];
        LOG.debug("Streaming file using buffer size {}.", bufferSize);
        for (int length = 0; ((length = input.read(buffer)) > 0); ) {
            output.write(buffer, 0, length);
        }
        result = true;
    }
    return result;
}
项目:httplite    文件:MiscHandle.java   
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;
}
项目:full-javaee-app    文件:CustomUtilities.java   
public static String getFileType(FileItemStream file) {
    if (file != null) {
        String fileName = file.getName().toLowerCase();
        String[] splitName = fileName.split("\\.", -1);
        String lastSplit = "." + splitName[splitName.length - 1];
        return lastSplit;
    }
    return null;
}
项目:full-javaee-app    文件:CustomUtilities.java   
public static byte[] fileItemStreamToByteArray(FileItemStream item, int docType) throws IOException, FileUploadException {
    if (item != null && docType > 0) {
        byte[] array = IOUtils.toByteArray(item.openStream());
        String[] types = new String[0];
        boolean returnVal = false;

        if (docType == 1) {
            types = new String[]{".jpg", ".jpeg", ".png"};
        } else if (docType == 2) {
            types = new String[]{".pdf", ".doc", ".docx"};
        } else if (docType == 3) {
            types = new String[]{".pdf", ".jpg", ".jpeg", ".png"};
        }

        for (String type : types) {
            if (getFileType(item).contains(type)) {
                returnVal = true;
            }
        }

        if (item.getName() != null && returnVal) {
            return array;
        }


    }
    throw new InvalidFormatException();
}
项目:nio-multipart    文件:FunctionalTest.java   
@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);
        }
    }

}
项目:nio-multipart    文件:FunctionalTest.java   
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());
        }

    }
项目:FOXopen    文件:MultipartUploadReader.java   
/**
 * Reads form values from the multipart request until a file is encountered. Field values are stored as strings for
 * retrieval using {@link #getFormFieldValue}.
 * @return  True if there is an upload file available to read via {@link #getUploadFileItem()}.
 */
public boolean readFormData() {
  mUploadFileItem = null;
  try {
    while (mItemIterator.hasNext()) {

      FileItemStream lCurrentItem = mItemIterator.next();
      /**
       * NOTE: the InputStream here is read here in a blocking way. Long upload hangs have been observed on live
       * environments at this point due to network issues. It should be possible to convert the stream to a
       * non-blocking stream at this point if required.
       */
      InputStream lItemInputStream = lCurrentItem.openStream();

      if (lCurrentItem.isFormField()) {
        //Read form values into the map
        String lParamName = lCurrentItem.getFieldName();
        String lFieldValue = Streams.asString(lItemInputStream);

        mFieldParamMap.put(lParamName, lFieldValue);
      }
      else {
        //We've hit the file field, so stop the read for now
        mUploadFileItem = lCurrentItem;
        break;
      }

      lItemInputStream.close();
    }

  }
  catch (IOException | FileUploadException e) {
    throw new ExInternal("Failed to read form data for the multipart request", e);
  }

  return mUploadFileItem != null;
}
项目:FOXopen    文件:UploadWorkItem.java   
private void initialiseUpload()
throws Throwable {

  try {
    FileItemStream lCurrentItem = mMultipartUploadReader.getUploadFileItem();
    if(lCurrentItem == null) {
      throw new ExInternal("No file available on the multipart upload reader - either reader is in an invalid state, or the upload contained no file field");
    }

    mItemInputStream = lCurrentItem.openStream();

    if (lCurrentItem.isFormField()) {
      //Skip form fields, they should have been read by the MultipartUploadReader
      Track.alert("UploadWorkItem", "Unexpected form field encountered when streaming upload");
    }
    else {
      mItemNonBlockingInputStream = new NonBlockingInputStream(mItemInputStream, BYTE_READ_QUANTITY, MAX_SUBSEQUENT_BUFFER_READS);

      String lFilename = lCurrentItem.getName();
      mUploadInfo.setOriginalFileLocation(lFilename);
      int lBeginningIndex = lFilename.lastIndexOf("\\");
      if ( lFilename != null && lBeginningIndex != -1 ) {
        // substr from that last occurrence of a back slash
        lFilename = lFilename.substring(lBeginningIndex + 1);
      }
      mUploadInfo.setFilename(lFilename);

      String lContentType = lCurrentItem.getContentType();
      mUploadInfo.setBrowserContentType(lContentType != null ? lContentType : "" );

      mStatus = READING_FILE_DATA;
      mLastReadTime = System.currentTimeMillis();
    }
  }
  catch (Throwable ex1) {
    throw ex1;
  }
}