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

项目: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);
        }

    }
项目: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;
}
项目: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()));
    }
}
项目: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());
        }
    }
}
项目: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");
}
项目: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;
}
项目: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;
}
项目: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);
        }
    }

}
项目:nexus-public    文件:HttpPartIteratorAdapter.java   
@Override
public Iterator<PartPayload> iterator() {
  try {
    final FileItemIterator itemIterator = new ServletFileUpload().getItemIterator(httpRequest);
    return new PayloadIterator(itemIterator);
  }
  catch (FileUploadException | IOException e) {
    throw new RuntimeException(e);
  }
}
项目:onecmdb    文件:ChangeUploadCommand.java   
private void getFileItem(HttpServletRequest request) throws FileUploadException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        throw new IllegalArgumentException("Not multipart...");
    }


        ServletFileUpload upload = new ServletFileUpload();

        List<String> mdrEntries = new ArrayList<String>();

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                System.out.println("Form field " + name + " with value "
                        + Streams.asString(stream) + " detected.");
            } else {
                System.out.println("File field " + name + " with file name "
                        + item.getName() + " detected.");
                // Process the input stream
            }
            String mdrEntry = handleInput(name, stream);
            mdrEntries.add(mdrEntry);
        }
        commitContent(mdrEntries);
}
项目:dojo-ibl    文件:UploadGameServlet.java   
protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    long gameId = 0l;
    String auth = null;
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(req);

        String json = "";
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(stream);
                if ("gameId".equals(name)) gameId = Long.parseLong(value);
                if ("auth".equals(name)) auth = value;

            } else {
                json = Streams.asString(stream);

            }
        }

        res.setContentType("text/plain");
        JSONObject jObject = new JSONObject(json);
        Object deserialized = JsonBeanDeserializer.deserialize(json);

        if (deserialized instanceof GamePackage && ((GamePackage) deserialized).getGame() != null)
            unpackGame((GamePackage) deserialized, req, auth);
        if (deserialized instanceof RunPackage && ((RunPackage) deserialized ).getRun() != null)
            unpackRun((RunPackage) deserialized, req, gameId, auth);

    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}
项目:domaintest    文件:HttpApiModule.java   
@Provides
@Singleton
Multimap<String, String> provideParameterMap(
    @RequestData("queryString") String queryString,
    @RequestData("postBody") Lazy<String> lazyPostBody,
    @RequestData("charset") String requestCharset,
    FileItemIterator multipartIterator) {
  // Calling request.getParameter() or request.getParameterMap() etc. consumes the POST body. If
  // we got the "postpayload" param we don't want to parse the body, so use only the query params.
  // Note that specifying both "payload" and "postpayload" will result in the "payload" param
  // being honored and the POST body being completely ignored.
  ImmutableMultimap.Builder<String, String> params = new ImmutableMultimap.Builder<>();
  Multimap<String, String> getParams = parseQuery(queryString);
  params.putAll(getParams);
  if (getParams.containsKey("postpayload")) {
    // Treat the POST body as if it was the "payload" param.
    return params.put("payload", nullToEmpty(lazyPostBody.get())).build();
  }
  // No "postpayload" so it's safe to consume the POST body and look for params there.
  if (multipartIterator == null) {  // Handle GETs and form-urlencoded POST requests.
    params.putAll(parseQuery(nullToEmpty(lazyPostBody.get())));
  } else {  // Handle multipart/form-data requests.
    try {
      while (multipartIterator != null && multipartIterator.hasNext()) {
        FileItemStream item = multipartIterator.next();
        try (InputStream stream = item.openStream()) {
          params.put(
              item.isFormField() ? item.getFieldName() : item.getName(),
              CharStreams.toString(new InputStreamReader(stream, requestCharset)));
        }
      }
    } catch (FileUploadException | IOException e) {
      // Ignore the failure and fall through to return whatever params we managed to parse.
    }
  }
  return params.build();
}
项目:domaintest    文件:RequestModule.java   
/** Provides a streaming {@link FileItemIterator} for parsing multipart/form-data requests. */
@Provides
FileItemIterator provideFileItemIterator(HttpServletRequest request) {
  try {
    return isMultipartContent(request) ? new ServletFileUpload().getItemIterator(request) : null;
  } catch (FileUploadException | IOException e) {
    return null;
  }
}
项目:Gplume    文件:Upload.java   
private Upload(final HttpServletRequest request) {
    this.upload = new ServletFileUpload();
    this.request = request;

    super.setStreamProvider(new InputStreamProvider() {

        @Override
        public InputStream getStream(String path) throws IOException {
            try {
                FileItemIterator iter = upload.getItemIterator(request);
                while (iter.hasNext()) {
                    FileItemStream stm = iter.next();
                    if (stm.getFieldName().equals(path)) {
                        return stm.openStream();
                    }
                }
            } catch (Exception e) {
                throw new IOException(e);
            }
            throw new IOException(path + " does not exists");
        }

        @Override
        public String getRealPath(String p) {
            throw new UnsupportedOperationException();
        }
    });

}
项目:tbx2rdf    文件:FileUploadServlet.java   
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        try {
            ServletFileUpload upload = new ServletFileUpload();
            res.setContentType("text/html");
            res.setCharacterEncoding("UTF-8");
            FileItemIterator iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    log.warning("Got a form field: " + item.getFieldName());
                } else {
                    log.warning("Got an uploaded file: " + item.getFieldName()+ ", name = " + item.getName());

                    // You now have the filename (item.getName() and the
                    // contents (which you can read from stream). Here we just
                    // print them back out to the servlet output stream, but you
                    // will probably want to do something more interesting (for
                    // example, wrap them in a Blob and commit them to the
                    // datastore).
/*                    int len;
                    byte[] buffer = new byte[8192];
                    while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
                        res.getOutputStream().write(buffer, 0, len);
                    }*/
                    String content = IOUtils.toString(stream, "UTF-8");
                    tbx2rdfServlet.formatOutput(res,content);

                }
            }
        } catch (Exception ex) {
            //throw new ServletException(ex);
        }
    }
项目:kurento-java    文件:RepositoryHttpServlet.java   
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp,
    OutputStream repoItemOutputStrem) throws IOException {

  log.debug("Multipart detected");

  ServletFileUpload upload = new ServletFileUpload();

  try {

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
      FileItemStream item = iter.next();
      String name = item.getFieldName();
      try (InputStream stream = item.openStream()) {
        if (item.isFormField()) {
          // TODO What to do with this?
          log.debug("Form field {} with value {} detected.", name, Streams.asString(stream));
        } else {

          // TODO Must we support multiple files uploading?
          log.debug("File field {} with file name detected.", name, item.getName());

          log.debug("Start to receive bytes (estimated bytes)",
              Integer.toString(req.getContentLength()));
          int bytes = IOUtils.copy(stream, repoItemOutputStrem);
          resp.setStatus(SC_OK);
          log.debug("Bytes received: {}", Integer.toString(bytes));
        }
      }
    }

  } catch (FileUploadException e) {
    throw new IOException(e);
  }
}
项目:OneCMDBwithMaven    文件:ChangeUploadCommand.java   
private void getFileItem(HttpServletRequest request) throws FileUploadException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        throw new IllegalArgumentException("Not multipart...");
    }


        ServletFileUpload upload = new ServletFileUpload();

        List<String> mdrEntries = new ArrayList<String>();

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                System.out.println("Form field " + name + " with value "
                        + Streams.asString(stream) + " detected.");
            } else {
                System.out.println("File field " + name + " with file name "
                        + item.getName() + " detected.");
                // Process the input stream
            }
            String mdrEntry = handleInput(name, stream);
            mdrEntries.add(mdrEntry);
        }
        commitContent(mdrEntries);
}
项目:jetbrick-all-1x    文件:FileUploaderUtils.java   
private static MultipartRequest asMultipartRequest(HttpServletRequest request) throws Exception {
    String encoding = request.getCharacterEncoding();

    MultipartRequest req = new MultipartRequest(request);
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(encoding);
    FileItemIterator it = upload.getItemIterator(request);

    while (it.hasNext()) {
        FileItemStream item = it.next();
        String fieldName = item.getFieldName();
        InputStream stream = item.openStream();
        try {
            if (item.isFormField()) {
                req.setParameter(fieldName, Streams.asString(stream, encoding));
            } else {
                String originalFilename = item.getName();
                File diskFile = getTempFile(originalFilename);
                OutputStream fos = new FileOutputStream(diskFile);

                try {
                    IoUtils.copy(stream, fos);
                } finally {
                    IoUtils.closeQuietly(fos);
                }

                FilePart filePart = new FilePart(fieldName, originalFilename, diskFile);
                req.addFile(filePart);
            }
        } finally {
            IoUtils.closeQuietly(stream);
        }
    }

    return req;
}
项目:avro-ui    文件:FileUploadServlet.java   
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();

    try{
        FileItemIterator iterator = upload.getItemIterator(request);
        if (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            String name = item.getFieldName();

            logger.debug("Uploading file '{}' with item name '{}'", item.getName(), name);

            InputStream stream = item.openStream();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Streams.copy(stream, out, true);

            byte[] data = out.toByteArray();

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(new String(data));
            response.flushBuffer();
        }
        else {
            logger.error("No file found in post request!");
            throw new RuntimeException("No file found in post request!");
        }
    }
    catch(Exception e){
        logger.error("Unexpected error in FileUploadServlet.doPost: ", e);
        throw new RuntimeException(e);
    }
}
项目:hexa.tools    文件:HexaGWTServlet.java   
@Override
protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
{
    resp.addHeader( "Pragma", "no-cache" );
    resp.addHeader( "Cache-Control", "no-cache" );

    // TODO get locale

    // TODO create a logger

    ServletFileUpload upload = new ServletFileUpload();

    try
    {
        FileItemIterator iterator = upload.getItemIterator( req );

        while( iterator.hasNext() )
        {
            FileItemStream stream = iterator.next();
            if( stream.getFieldName().equals( "payload" ) )
            {
                String response = processPayload( stream.openStream() );
                resp.getWriter().write( response );
                return;
            }
        }
    }
    catch( Exception e )
    {
        resp.getWriter().write( "Exception during POST processing : " + e.getMessage() );
        e.printStackTrace();
        return;
    }

    resp.getWriter().write( "INSUFICIENT PAYLOAD" );
}
项目:kaa    文件:FileUpload.java   
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  //CHECKSTYLE:ON
  ServletFileUpload upload = new ServletFileUpload();

  try {
    FileItemIterator iter = upload.getItemIterator(request);
    if (iter.hasNext()) {
      FileItemStream item = iter.next();
      String name = item.getFieldName();

      LOG.debug("Uploading file '{}' with item name '{}'", item.getName(), name);

      InputStream stream = item.openStream();

      // Process the input stream
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      Streams.copy(stream, out, true);

      byte[] data = out.toByteArray();

      cacheService.uploadedFile(name, data);
    } else {
      LOG.error("No file found in post request!");
      throw new RuntimeException("No file found in post request!");
    }
  } catch (Exception ex) {
    LOG.error("Unexpected error in FileUpload.doPost: ", ex);
    throw new RuntimeException(ex);
  }

}
项目:raml-tester    文件:FormDecoder.java   
private Values decodeMultipart(RamlRequest request) {
    try {
        final Values values = new Values();
        final RamlRequestFileUploadContext context = new RamlRequestFileUploadContext(request);
        final FileItemIterator iter = new ServletFileUpload().getItemIterator(context);
        while (iter.hasNext()) {
            final FileItemStream itemStream = iter.next();
            values.addValue(itemStream.getFieldName(), valueOf(itemStream));
        }
        return values;
    } catch (IOException | FileUploadException e) {
        throw new IllegalArgumentException("Could not parse multipart request", e);
    }
}
项目:mev    文件:ImportProjectCommand.java   
protected void internalImport(
    HttpServletRequest    request,
    Properties            options,
    long                  projectID
) throws Exception {

    String url = null;

    ServletFileUpload upload = new ServletFileUpload();

    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName().toLowerCase();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            if (name.equals("url")) {
                url = Streams.asString(stream);
            } else {
                options.put(name, Streams.asString(stream));
            }
        } else {
            String fileName = item.getName().toLowerCase();
            try {
                ProjectManager.getSingleton().importProject(projectID, stream, !fileName.endsWith(".tar"));
            } finally {
                stream.close();
            }
        }
    }

    if (url != null && url.length() > 0) {
        internalImportURL(request, options, projectID, url);
    }
}
项目:camunda-bpm-platform    文件:MultipartPayloadProvider.java   
protected void parseRequest(MultipartFormData multipartFormData, FileUpload fileUpload, RestMultipartRequestContext requestContext) {
  try {
    FileItemIterator itemIterator = fileUpload.getItemIterator(requestContext);
    while (itemIterator.hasNext()) {
      FileItemStream stream = itemIterator.next();
      multipartFormData.addPart(new FormPart(stream));
    }
  } catch (Exception e) {
    throw new RestException(Status.BAD_REQUEST, e, "multipart/form-data cannot be processed");

  }
}
项目:Equella    文件:SuperDuperFilter.java   
@Override
public void doFilter(HttpExchange exchange, Chain chain) throws IOException
{
    final Map<String, List<String>> params = parseGetParameters(exchange);
    Map<String, Pair<String, File>> streams = null;

    if( HttpExchangeUtils.isPost(exchange) )
    {
        if( HttpExchangeUtils.isMultipartContent(exchange) )
        {
            streams = new HashMap<String, Pair<String, File>>();

            try
            {
                FileItemIterator ii = new FileUpload().getItemIterator(new ExchangeRequestContext(exchange));
                while( ii.hasNext() )
                {
                    final FileItemStream is = ii.next();
                    final String name = is.getFieldName();
                    try( InputStream stream = is.openStream() )
                    {
                        if( !is.isFormField() )
                        {
                            // IE passes through the full path of the file,
                            // where as Firefox only passes through the
                            // filename. We only need the filename, so
                            // ensure that we string off anything that looks
                            // like a path.
                            final String filename = STRIP_PATH_FROM_FILENAME.matcher(is.getName()).replaceFirst(
                                "$1");
                            final File tempfile = File.createTempFile("equella-manager-upload", "tmp");
                            tempfile.getParentFile().mkdirs();
                            streams.put(name, new Pair<String, File>(filename, tempfile));

                            try( OutputStream out = new BufferedOutputStream(new FileOutputStream(tempfile)) )
                            {
                                ByteStreams.copy(stream, out);
                            }
                        }
                        else
                        {
                            addParam(params, name, Streams.asString(stream));
                        }
                    }
                }
            }
            catch( Exception t )
            {
                throw new RuntimeException(t);
            }
        }
        else
        {
            try( InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), "UTF-8") )
            {
                BufferedReader br = new BufferedReader(isr);
                String query = br.readLine();

                parseQuery(query, params);
            }
        }
    }

    exchange.setAttribute(PARAMS_KEY, params);
    exchange.setAttribute(MULTIPART_STREAMS_KEY, streams);
    // attributes seem to last the life of a session... I don't know why...
    exchange.setAttribute("error", null);

    chain.doFilter(exchange);
}
项目:full-javaee-app    文件:SchoolResumeUploadServlet.java   
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Creates EntityManager to query database
    EntityManager em = EMFUtil.getEMFactory().createEntityManager();

    // Transactions are employed to roll back changes in case of error and
    // ensure data integrity
    EntityTransaction trans = em.getTransaction();

    // Creates a session object and retrieves entities
    HttpSession session = request.getSession();
    int candidateID = (int) session.getAttribute("candidateID");
    Candidates candidate = em.find(Candidates.class, candidateID);
    String source = request.getParameter("source");

    System.out.println(source);

    ServletFileUpload upload = new ServletFileUpload();

    try {
        FileItemIterator iterator = upload.getItemIterator(request);

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.getName() != null) {
                if (item.getName().contains(".pdf") || item.getName().contains(".doc")) {
                    byte[] file = IOUtils.toByteArray(item.openStream());
                    candidate.setResume(file);

                       trans.begin();
                       em.merge(candidate);
                       trans.commit();

                    // For logging activity
                    SchoolLoginLogs loginLog = (SchoolLoginLogs) session.getAttribute("loginLog");
                    if (loginLog != null) {
                        SchoolActivityLogs activityLog = new SchoolActivityLogs();
                        activityLog.setSchoolLoginLogID(loginLog.getSchoolLoginLogID());
                        activityLog.setTime(Clock.getCurrentTime());
                        activityLog.setCandidateID(candidateID);
                        activityLog.setCandidate(candidate);
                        activityLog.setSchoolActivity("Uploaded Resume");
                        SchoolAccountDataAccessObject.persistActivityLog(activityLog);
                    }

                    session.setAttribute("resumeSuccess", "Resume uploaded!");
                    session.setAttribute("resume", "true");
                    session.setAttribute("candidate", candidate);
                    session.setAttribute("loginLog", loginLog);
                } else {
                    String resumeError = "Please upload a resume in PDF or DOC/DOCX format.";
                    session.setAttribute("resume", "true");
                    session.setAttribute("resumeError", resumeError);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error uploading resume");
    } finally {
        em.close();
        response.sendRedirect("schools/school-candidate-profile.jsp");
    }
}
项目:full-javaee-app    文件:SchoolPictureUploadServlet.java   
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    EntityManager em = EMFUtil.getEMFactory().createEntityManager();
    EntityTransaction trans = em.getTransaction();

    HttpSession session = request.getSession();
    int candidateID = (int) session.getAttribute("candidateID");

    Candidates candidate = em.find(Candidates.class, candidateID);

    ServletFileUpload upload = new ServletFileUpload();

    try {
        FileItemIterator iterator = upload.getItemIterator(request);

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.getName() != null) {
                if (item.getName().toLowerCase().contains(".jpg") || item.getName().toLowerCase().contains(".jpeg")
                        || item.getName().toLowerCase().contains(".png")) {
                    byte[] file = IOUtils.toByteArray(item.openStream());
                    candidate.setPhoto(file);
                    trans.begin();
                    candidate = em.merge(candidate);
                    trans.commit();

                    session.setAttribute("resume", "true");
                    session.setAttribute("resumeSuccess", "Picture uploaded!");
                    session.setAttribute("candidate", candidate);

                    // For logging activity
                    SchoolLoginLogs loginLog = (SchoolLoginLogs) session.getAttribute("loginLog");
                    if (loginLog != null) {
                        SchoolActivityLogs activityLog = new SchoolActivityLogs();
                        activityLog.setSchoolLoginLogID(loginLog.getSchoolLoginLogID());
                        activityLog.setTime(Clock.getCurrentTime());
                        activityLog.setCandidateID(candidateID);
                        activityLog.setCandidate(candidate);
                        activityLog.setSchoolActivity("Uploaded Picture");
                        SchoolAccountDataAccessObject.persistActivityLog(activityLog);
                    }

                    session.setAttribute("resume", "true");
                    session.setAttribute("resumeSuccess", "Picture uploaded!");
                    session.setAttribute("candidate", candidate);
                    response.sendRedirect("schools/school-candidate-profile.jsp");
                } else {
                    String resumeError = "Please upload a picture in PNG or JPG/JPEG format.";
                    session.setAttribute("resume", "true");
                    session.setAttribute("resumeError", resumeError);
                    response.sendRedirect("schools/school-candidate-profile.jsp");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        session.setAttribute("resumeError", "An error occurred.");
        response.sendRedirect("schools/school-candidate-profile.jsp");
    } finally {
        em.close();
    }
}
项目:AndServer    文件:HttpFileUpload.java   
public FileItemIterator getItemIterator(HttpRequest request) throws FileUploadException, IOException {
    return getItemIterator(new HttpUploadContext((HttpEntityEnclosingRequest) request));
}
项目: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;
}
项目:megaphone    文件:MultipartUploadTest.java   
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        List<String> files = new ArrayList<>();
        ServletFileUpload upload = new ServletFileUpload();
        // Parse the request
        FileItemIterator iter = null;
        try {
            iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                try (InputStream stream = item.openStream()) {

                    if (item.isFormField()) {
                        LOGGER.debug("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
                        incrementStringsProcessed();
                    } else {
                        LOGGER.debug("File field " + name + " with file name " + item.getName() + " detected.");
                        // Process the input stream
                        File tmpFile = File.createTempFile(UUID.randomUUID().toString() + "_MockUploadServlet", ".tmp");
                        tmpFile.deleteOnExit();
                        try (OutputStream os = new FileOutputStream(tmpFile)) {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = stream.read(buffer)) != -1) {
                                os.write(buffer, 0, bytesRead);
                            }
                            incrementFilesProcessed();
                            files.add(tmpFile.getAbsolutePath());
                        }
                    }
                }
            }
        } catch (FileUploadException e) {

        }
        try (Writer w = response.getWriter()) {
            w.write(Integer.toString(getFilesProcessed()));
            resetFilesProcessed();
            resetStringsProcessed();
            w.write("||");
            w.write(files.toString());
        }
    } else {
        try (Writer w = response.getWriter()) {
            w.write(Integer.toString(getFilesProcessed()));
            resetFilesProcessed();
            resetStringsProcessed();
            w.write("||");
        }
    }
}
项目:aramcomp    文件:FormBasedFileUtil.java   
/**
 * 파일을 Upload 처리한다.
 * 
 * @param request
 * @param where
 * @param maxFileSize
 * @return
 * @throws Exception
 */
public static List<FormBasedFileVo> uploadFiles(
        HttpServletRequest request, 
        String where, 
        long maxFileSize) throws Exception {

    List<FormBasedFileVo> list = new ArrayList<FormBasedFileVo>();

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileSizeMax(maxFileSize); // SizeLimitExceededException

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                // System.out.println("Form field '" + name + "' with value '" + Streams.asString(stream) +
                // "' detected.");
                LOG.info("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
            } else {
                // System.out.println("File field '" + name + "' with file name '" + item.getName() + "' detected.");
                LOG.info("File field '" + name + "' with file name '" + item.getName() + "' detected.");

                if ("".equals(item.getName())) {
                    continue;
                }

                // Process the input stream
                FormBasedFileVo vo = new FormBasedFileVo();

                String tmp = item.getName();

                if (tmp.lastIndexOf("\\") >= 0) {
                    tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
                }

                vo.setFileName(tmp);
                vo.setContentType(item.getContentType());
                vo.setServerSubPath(getTodayString());
                vo.setPhysicalName(getPhysicalFileName());

                if (tmp.lastIndexOf(".") >= 0) {
                    vo.setPhysicalName(vo.getPhysicalName() + tmp.substring(tmp.lastIndexOf(".")));
                }

                long size = saveFile(stream,
                        new File(WebUtil.filePathBlackList(where) + SEPERATOR + vo.getServerSubPath() + SEPERATOR + vo.getPhysicalName()));

                vo.setSize(size);

                list.add(vo);
            }
        }
    } else {
        throw new IOException("form's 'enctype' attribute have to be 'multipart/form-data'");
    }

    return list;
}
项目:struts2    文件:JakartaStreamMultiPartRequest.java   
/**
 * Processes the upload.
 *
 * @param request the servlet request
 * @param saveDir location of the save dir
 * @throws Exception
 */
private void processUpload(HttpServletRequest request, String saveDir) throws Exception {

    // Sanity check that the request is a multi-part/form-data request.
    if (ServletFileUpload.isMultipartContent(request)) {

        // Sanity check on request size.
        boolean requestSizePermitted = isRequestSizePermitted(request);

        // Interface with Commons FileUpload API
        // Using the Streaming API
        ServletFileUpload servletFileUpload = new ServletFileUpload();
        FileItemIterator i = servletFileUpload.getItemIterator(request);

        // Iterate the file items
        while (i.hasNext()) {
            try {
                FileItemStream itemStream = i.next();

                // If the file item stream is a form field, delegate to the
                // field item stream handler
                if (itemStream.isFormField()) {
                    processFileItemStreamAsFormField(itemStream);
                }

                // Delegate the file item stream for a file field to the
                // file item stream handler, but delegation is skipped
                // if the requestSizePermitted check failed based on the
                // complete content-size of the request.
                else {

                    // prevent processing file field item if request size not allowed.
                    // also warn user in the logs.
                    if (!requestSizePermitted) {
                        addFileSkippedError(itemStream.getName(), request);
                        LOG.warn("Skipped stream '{}', request maximum size ({}) exceeded.", itemStream.getName(), maxSize);
                        continue;
                    }

                    processFileItemStreamAsFileField(itemStream, saveDir);
                }
            } catch (IOException e) {
                LOG.warn("Error occurred during process upload", e);
            }
        }
    }
}
项目:httplite    文件:RecordedUpload.java   
public FileItemIterator getItemIterator() throws FileUploadException,IOException{
    return super.getItemIterator(this);
}
项目:full-javaee-app    文件:SchoolResumeUploadServlet.java   
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Creates EntityManager to query database
    EntityManager em = EMFUtil.getEMFactory().createEntityManager();

    // Transactions are employed to roll back changes in case of error and
    // ensure data integrity
    EntityTransaction trans = em.getTransaction();

    // Creates a session object and retrieves entities
    HttpSession session = request.getSession();
    int candidateID = (int) session.getAttribute("candidateID");
    Candidates candidate = em.find(Candidates.class, candidateID);
    String source = request.getParameter("source");

    System.out.println(source);

    ServletFileUpload upload = new ServletFileUpload();

    try {
        FileItemIterator iterator = upload.getItemIterator(request);

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.getName() != null) {
                if (item.getName().contains(".pdf") || item.getName().contains(".doc")) {
                    byte[] file = IOUtils.toByteArray(item.openStream());
                    candidate.setResume(file);

                       trans.begin();
                       em.merge(candidate);
                       trans.commit();

                    // For logging activity
                    SchoolLoginLogs loginLog = (SchoolLoginLogs) session.getAttribute("loginLog");
                    if (loginLog != null) {
                        SchoolActivityLogs activityLog = new SchoolActivityLogs();
                        activityLog.setSchoolLoginLogID(loginLog.getSchoolLoginLogID());
                        activityLog.setTime(Clock.getCurrentTime());
                        activityLog.setCandidateID(candidateID);
                        activityLog.setCandidate(candidate);
                        activityLog.setSchoolActivity("Uploaded Resume");
                        SchoolAccountDataAccessObject.persistActivityLog(activityLog);
                    }

                    session.setAttribute("resumeSuccess", "Resume uploaded!");
                    session.setAttribute("resume", "true");
                    session.setAttribute("candidate", candidate);
                    session.setAttribute("loginLog", loginLog);
                } else {
                    String resumeError = "Please upload a resume in PDF or DOC/DOCX format.";
                    session.setAttribute("resume", "true");
                    session.setAttribute("resumeError", resumeError);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error uploading resume");
    } finally {
        em.close();
        response.sendRedirect("schools/school-candidate-profile.jsp");
    }
}
项目:full-javaee-app    文件:SchoolPictureUploadServlet.java   
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    EntityManager em = EMFUtil.getEMFactory().createEntityManager();
    EntityTransaction trans = em.getTransaction();

    HttpSession session = request.getSession();
    int candidateID = (int) session.getAttribute("candidateID");

    Candidates candidate = em.find(Candidates.class, candidateID);

    ServletFileUpload upload = new ServletFileUpload();

    try {
        FileItemIterator iterator = upload.getItemIterator(request);

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.getName() != null) {
                if (item.getName().toLowerCase().contains(".jpg") || item.getName().toLowerCase().contains(".jpeg")
                        || item.getName().toLowerCase().contains(".png")) {
                    byte[] file = IOUtils.toByteArray(item.openStream());
                    candidate.setPhoto(file);
                    trans.begin();
                    candidate = em.merge(candidate);
                    trans.commit();

                    session.setAttribute("resume", "true");
                    session.setAttribute("resumeSuccess", "Picture uploaded!");
                    session.setAttribute("candidate", candidate);

                    // For logging activity
                    SchoolLoginLogs loginLog = (SchoolLoginLogs) session.getAttribute("loginLog");
                    if (loginLog != null) {
                        SchoolActivityLogs activityLog = new SchoolActivityLogs();
                        activityLog.setSchoolLoginLogID(loginLog.getSchoolLoginLogID());
                        activityLog.setTime(Clock.getCurrentTime());
                        activityLog.setCandidateID(candidateID);
                        activityLog.setCandidate(candidate);
                        activityLog.setSchoolActivity("Uploaded Picture");
                        SchoolAccountDataAccessObject.persistActivityLog(activityLog);
                    }

                    session.setAttribute("resume", "true");
                    session.setAttribute("resumeSuccess", "Picture uploaded!");
                    session.setAttribute("candidate", candidate);
                    response.sendRedirect("schools/school-candidate-profile.jsp");
                } else {
                    String resumeError = "Please upload a picture in PNG or JPG/JPEG format.";
                    session.setAttribute("resume", "true");
                    session.setAttribute("resumeError", resumeError);
                    response.sendRedirect("schools/school-candidate-profile.jsp");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        session.setAttribute("resumeError", "An error occurred.");
        response.sendRedirect("schools/school-candidate-profile.jsp");
    } finally {
        em.close();
    }
}