Java 类org.apache.commons.fileupload.servlet.ServletFileUpload 实例源码

项目:scaffold    文件:Uploader.java   
/**
 * 文件上传处理类
 *
 * @return {@link UploadResult}
 * @throws Exception 抛出异常
 */
public UploadResult upload() throws Exception {
    boolean multipartContent = ServletFileUpload.isMultipartContent(request);
    if (!multipartContent) {
        throw new RuntimeException("上传表单enctype类型设置错误");
    }

    List<TextFormResult> textFormResultList = Lists.newArrayList();
    List<FileFormResult> fileFormResultList = Lists.newArrayList();

    List<FileItem> fileItems = upload.parseRequest(request);
    for (FileItem item : fileItems) {
        if (item.isFormField())
            textFormResultList.add(processFormField(item));
        else
            fileFormResultList.add(processUploadedFile(item));
    }
    return new UploadResult(textFormResultList, fileFormResultList);
}
项目:iBase4J-Common    文件:UploadUtil.java   
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
项目:automat    文件:UploadUtil.java   
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
项目:mumu    文件:UploadUtil.java   
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
项目:iBase4J    文件:UploadUtil.java   
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
项目:JAVA-    文件:UploadUtil.java   
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
项目:mumu-core    文件:UploadUtil.java   
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
项目:osframe    文件:UploadUtil.java   
/** 获取所有文本域 */
public static List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
项目:xslweb    文件:RequestSerializer.java   
private List<FileItem> getMultipartContentItems() throws IOException, FileUploadException {
  List<FileItem> items = null;
  boolean isMultipart = ServletFileUpload.isMultipartContent(req);    
  if (isMultipart) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(0);
    reposDir = new File(FileUtils.getTempDirectory(), File.separatorChar + UUID.randomUUID().toString());
    if (!reposDir.mkdirs()) {
      throw new XSLWebException(String.format("Could not create DiskFileItemFactory repository directory (%s)", reposDir.getAbsolutePath()));
    }
    factory.setRepository(reposDir);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(1024 * 1024 * webApp.getMaxUploadSize());
    items = upload.parseRequest(req);      
  }
  return items;
}
项目:jawn    文件:JawnServletContext.java   
/**
 * Gets the FileItemIterator of the input.
 * 
 * Can be used to process uploads in a streaming fashion. Check out:
 * http://commons.apache.org/fileupload/streaming.html
 * 
 * @return the FileItemIterator of the request or null if there was an
 *         error.
 */
public Optional<List<FormItem>> parseRequestMultiPartItems(String encoding) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE/*Constants.Params.maxUploadSize.name()*/));//Configuration.getMaxUploadSize());
    factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); //Configuration.getTmpDir());
    //README the file for tmpdir *MIGHT* need to go into Properties

    ServletFileUpload upload = new ServletFileUpload(factory);

    if(encoding != null)
        upload.setHeaderEncoding(encoding);
    upload.setFileSizeMax(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE));

    try {
        List<FormItem> items = upload.parseRequest(request)
                .stream()
                .map(item -> new ApacheFileItemFormItem(item))
                .collect(Collectors.toList());
        return Optional.of(items);
    } catch (FileUploadException e) {
        //"Error while trying to process mulitpart file upload"
        //README: perhaps some logging
    }
    return Optional.empty();
}
项目:Breakpoint-http    文件:IndexController.java   
/**
 * 上传文件
 *
 * @param param
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity fileUpload(MultipartFileParam param, HttpServletRequest request) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        logger.info("上传文件start。");
        try {
            // 方法1
            //storageService.uploadFileRandomAccessFile(param);
            // 方法2 这个更快点
            storageService.uploadFileByMappedByteBuffer(param);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("文件上传失败。{}", param.toString());
        }
        logger.info("上传文件end。");
    }
    return ResponseEntity.ok().body("上传成功。");
}
项目:urule    文件:FrameServletHandler.java   
public void importProject(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletContext servletContext = req.getSession().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    ServletFileUpload upload = new ServletFileUpload(factory);
    InputStream inputStream=null;
    boolean overwriteProject=true;
    List<FileItem> items = upload.parseRequest(req);
    if(items.size()==0){
        throw new ServletException("Upload file is invalid.");
    }
    for(FileItem item:items){
        String name=item.getFieldName();
        if(name.equals("overwriteProject")){
            String overwriteProjectStr=new String(item.get());
            overwriteProject=Boolean.valueOf(overwriteProjectStr);
        }else if(name.equals("file")){
            inputStream=item.getInputStream();
        }
    }
    repositoryService.importXml(inputStream,overwriteProject);
    IOUtils.closeQuietly(inputStream);
    resp.sendRedirect(req.getContextPath()+"/urule/frame");
}
项目:urule    文件:PackageServletHandler.java   
public void importExcelTemplate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    DiskFileItemFactory factory=new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(req);
    Iterator<FileItem> itr = items.iterator();
    List<Map<String,Object>> mapData=null;
    while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        String name=item.getFieldName();
        if(!name.equals("file")){
            continue;
        }
        InputStream stream=item.getInputStream();
        mapData=parseExcel(stream);
        httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData);
        stream.close();
        break;
    }
    httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData);
    writeObjectToJson(resp, mapData);
}
项目:convertigo-engine    文件:UploadService.java   
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart)
        throw new IllegalArgumentException("Not multipart content!");

    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));

    // Process the uploaded items
    handleFormFields(request);
    for (FileItem item : items) {
        doUpload(request, document, item);
    }
}
项目:xmall    文件:QiniuUtil.java   
public static String isValidImage(HttpServletRequest request, MultipartFile file){
    //最大文件大小
    long maxSize = 5242880;
    //定义允许上传的文件扩展名
    HashMap<String, String> extMap = new HashMap<String, String>();
    extMap.put("image", "gif,jpg,jpeg,png,bmp");

    if(!ServletFileUpload.isMultipartContent(request)){
        return "请选择文件";
    }

    if(file.getSize() > maxSize){
        return "上传文件大小超过5MB限制";
    }
    //检查扩展名
    String fileName=file.getOriginalFilename();
    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
        return "上传文件扩展名是不允许的扩展名\n只允许" + extMap.get("image") + "格式";
    }

    return "valid";
}
项目:oryx2    文件:AbstractOryxResource.java   
private Collection<Part> parseMultipartWithCommonsFileUpload(HttpServletRequest request) throws IOException {
  if (sharedFileItemFactory.get() == null) {
    // Not a big deal if two threads actually set this up
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(
        1 << 16, (File) servletContext.getAttribute("javax.servlet.context.tempdir"));
    fileItemFactory.setFileCleaningTracker(
        FileCleanerCleanup.getFileCleaningTracker(servletContext));
    sharedFileItemFactory.compareAndSet(null, fileItemFactory);
  }

  try {
    return new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request)
        .stream().map(FileItemPart::new).collect(Collectors.toList());
  } catch (FileUploadException e) {
    throw new IOException(e.getMessage());
  }
}
项目:carbon    文件:MultipartFormKeyValueRequestMapper.java   
public Map<String, Object> map(HttpServletRequest request) {
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setSizeMax(20 * 1024);
    upload.setFileSizeMax(10 * 1024);

    List<FileItem> items;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        throw new RequestMappingException("", e);
    }

    return items.stream().map(item -> {
        String key = item.getFieldName();
        if (item.isFormField()) {
            String value = item.getString();
            return new SimpleKeyValue<String, Object>(key, value);
        } else {
            return new SimpleKeyValue<String, Object>(key, item);
        }
    }).collect(Collectors.toMap(
            SimpleKeyValue::getKey,
            SimpleKeyValue::getValue
    ));
}
项目:openbravo-brazil    文件:VariablesBase.java   
/**
 * Basic constructor that takes the request object and saves it to be used by the subsequent
 * methods
 * 
 * @param request
 *          HttpServletRequest object originating from the user request.
 */
@SuppressWarnings("unchecked")
public VariablesBase(HttpServletRequest request) {
  if (request == null) {
    // logging exception to obtain stack trace to pinpoint the cause
    log4j.warn("Creating a VariablesBase with a null request", new Exception());
    this.session = new HttpSessionWrapper();
    this.isMultipart = false;
  } else {
    this.session = request.getSession(true);
    this.httpRequest = request;
    this.isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
    if (isMultipart) {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // factory.setSizeThreshold(yourMaxMemorySize);
      // factory.setRepositoryPath(yourTempDirectory);
      ServletFileUpload upload = new ServletFileUpload(factory);
      // upload.setSizeMax(yourMaxRequestSize);
      try {
        items = upload.parseRequest(request);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
}
项目:webframework    文件:SimpleRequestObject.java   
public SimpleRequestObject(final HttpMethod method,
        final HttpServletRequest req,
        final File tempFolder,
        final long maxDiskFile,
        final int maxMemFile,
        final boolean allowDiskCache) {
    this.method = method;
    this.req = req;
    if(ServletFileUpload.isMultipartContent(req)) {
        this.variableRequestHandler = new VRFile();
    } else {
        this.variableRequestHandler = new VRNormal();
    }
    this.variableRequestHandler.setFileTempDirectory(tempFolder);
    this.variableRequestHandler.setMaxFileUploadSize(maxDiskFile);
    this.variableRequestHandler.setMaxMemFileSize(maxMemFile);
    this.variableRequestHandler.allowFilesOnDisk(allowDiskCache);
    final javax.servlet.http.Cookie[] cs = this.req.getCookies();
    if(cs != null) {
        for(final javax.servlet.http.Cookie c: cs) {
            cookies.put(c.getName(), new HttpCookie(c));
        }
    }
}
项目:giiwa    文件:Model.java   
/**
 * Copy all request params from the model.
 *
 * @param m
 *            the model of source
 */
final public void copy(Model m) {

    this.req = m.req;
    this.resp = m.resp;
    this.contentType = m.contentType;
    this.context = m.context;
    this.lang = m.lang;
    this.locale = m.locale;
    this.login = m.login;
    this.method = m.method;
    this.path = m.path;
    this.sid = m.sid;
    this.uri = m.uri;
    this._multipart = ServletFileUpload.isMultipartContent(req);

    if (this._multipart) {
        this.uploads = m.getFiles();
    }

}
项目:simbest-cores    文件:CustomMultipartResolver.java   
public List<FileItem> checkContentType(HttpServletRequest request, String encoding){
    if(null != fileTypes && fileTypes.size() > 0){
        FileUpload fileUpload = prepareFileUpload(encoding);
        try {
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            for (FileItem item : fileItems) {
                if(!item.isFormField()) { //必须是文件
                    log.debug("client want to upload file with name: " + item.getName());
                    log.debug("client want to upload file with type: " + item.getContentType());
                    if (!fileTypes.contains(AppFileUtils.getFileExtByName(item.getName()))) {
                        for(String fileType : fileTypes){
                            log.error("Allowd fileType is: "+fileType);
                        }
                        throw new NotAllowUploadFileTypeException("Not allow upload file type exception occur, client upload type is: "+AppFileUtils.getFileExtByName(item.getName()));
                    }
                }
            }
            return fileItems;
        } catch (FileUploadException e) {
            throw new NotAllowUploadFileTypeException("Not allow upload file type exception occur... \r\n" + e.getMessage());
        }
    }
    return null;
}
项目:bisis-v4    文件:FileManagerServlet.java   
public void doPost(HttpServletRequest req, HttpServletResponse res) {
  boolean isMultipart = ServletFileUpload.isMultipartContent(req);    
  if (!isMultipart && req.getParameter("operation").equals("delete")){      
    handleDelete(req, res);
  }
  if (!isMultipart && req.getParameter("operation").equals("deleteAllForRecord")){      
   handleDeleteAllForRecord(req, res);
 }
  else{     
    try {
      handleUpload(req, res);
      writeOK(res);
    } catch (FileUploadException ex) {           
      log.fatal(ex);
      writeError(res, ex);
    }
  }
}
项目:azkaban    文件:MultipartParser.java   
@SuppressWarnings("unchecked")
public Map<String, Object> parseMultipart(HttpServletRequest request)
    throws IOException, ServletException {
  ServletFileUpload upload = new ServletFileUpload(_uploadItemFactory);
  List<FileItem> items = null;
  try {
    items = upload.parseRequest(request);
  } catch (FileUploadException e) {
    throw new ServletException(e);
  }

  Map<String, Object> params = new HashMap<String, Object>();
  for (FileItem item : items) {
    if (item.isFormField())
      params.put(item.getFieldName(), item.getString());
    else
      params.put(item.getFieldName(), item);
  }
  return params;
}
项目:webwheel    文件:JsonResult.java   
public void render() throws IOException {
    ctx.getResponse().setCharacterEncoding(charset);
    String s = toString();
    if (wrapMultipart && ServletFileUpload.isMultipartContent(ctx.getRequest()) && !"XMLHttpRequest".equals(ctx.getRequest().getHeader("X-Requested-With"))) {
        ctx.getResponse().setContentType(contentType == null ? "text/html" : contentType);
        PrintWriter pw = ctx.getResponse().getWriter();
        final String s1 = "<textarea>";
        final String s2 = "</textarea>";
        pw.write(s1, 0, s1.length());
        pw.write(s);
        pw.write(s2, 0, s2.length());
        return;
    }
    String ct = contentType;
    if (ct == null) {
        ct = "application/json";
        String ua = ctx.getRequest().getHeader("User-Agent");
        if (ua != null && ua.contains("MSIE")) {
            ct = "text/plain;charset=" + charset;
        }
    }
    ctx.getResponse().setContentType(ct);
    ctx.getResponse().getWriter().write(s);
}
项目: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;
}
项目:kc-rice    文件:RequestParser.java   
public List<String> getParameterNames() {
    List<String> names = new ArrayList<String>();
    boolean isMultipart = ServletFileUpload.isMultipartContent(this.getRequest());
    if (isMultipart) {
    parseRequest(this.getRequest());
    Map paramMap = ((Map)request.getAttribute(PARSED_MULTI_REQUEST_KEY));
    for (Iterator iterator = paramMap.keySet().iterator(); iterator.hasNext();) {
        String parameterName = (String)iterator.next();
        names.add(parameterName);
    }
    } else { 
    Enumeration<String> nameEnum = getRequest().getParameterNames();
    while (nameEnum.hasMoreElements()) {
        names.add(nameEnum.nextElement());
    }
    }
    return names;
}
项目:FOXopen    文件:MultipartUploadReader.java   
/**
 * Creates a new Reader for reading the given HTTP request. This must be a multipart request.
 * @param pFoxRequest
 */
public MultipartUploadReader(FoxRequest pFoxRequest) {
  try {
    // New file upload handler
    mServletFileUploadUpload = new ServletFileUpload();

    // Create a progress listener for this upload
    mFiletransferProgressListener = new FiletransferProgressListener();

    // Attach the progress listener to this upload
    mServletFileUploadUpload.setProgressListener(mFiletransferProgressListener);
    //mUploadInfo.setProgressListener(mFiletransferProgressListener);

    // Parse the upload request
    mItemIterator = mServletFileUploadUpload.getItemIterator(pFoxRequest.getHttpRequest());
  }
  catch (Throwable ex) {
    throw new ExInternal("Error encountered while trying to initialise a file upload work item.\nOriginal error: " + ex.getMessage());
  }
}
项目:FOXopen    文件:UploadServlet.java   
private FoxResponse processReceive(RequestContext pRequestContext) {

    UploadProcessor lUploadProcessor;
    try {
      FoxRequest lFoxRequest = pRequestContext.getFoxRequest();
      // Check that we have a multipart file upload request
      if (!ServletFileUpload.isMultipartContent(lFoxRequest.getHttpRequest())) {
        throw new ExInternal("File upload must be a multipart request");
      }

      lUploadProcessor = new UploadProcessor(pRequestContext);
    }
    catch (Throwable th) {
      //Catch errors caused by an invalid request, missing UploadInfo, etc
      return generateErrorResponse(th, null, true);
    }

    //Start receiving the upload
    //UploadProcessor does its own error handling
    return lUploadProcessor.processUpload(pRequestContext);
  }
项目: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;
}
项目:search    文件:SolrRequestParsers.java   
@Override
public SolrParams parseParamsAndFillStreams( 
    final HttpServletRequest req, ArrayList<ContentStream> streams ) throws Exception
{
  String method = req.getMethod().toUpperCase(Locale.ROOT);
  if ("GET".equals(method) || "HEAD".equals(method) 
      || (("PUT".equals(method) || "DELETE".equals(method))
          && (req.getRequestURI().contains("/schema")
              || req.getRequestURI().contains("/config")))) {
    return parseQueryString(req.getQueryString());
  }
  if ("POST".equals( method ) ) {
    if (formdata.isFormData(req)) {
      return formdata.parseParamsAndFillStreams(req, streams);
    }
    if (ServletFileUpload.isMultipartContent(req)) {
      return multipart.parseParamsAndFillStreams(req, streams);
    }
    if (req.getContentType() != null) {
      return raw.parseParamsAndFillStreams(req, streams);
    }
    throw new SolrException(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "Must specify a Content-Type header with POST requests");
  }
  throw new SolrException(ErrorCode.BAD_REQUEST, "Unsupported method: " + method + " for request " + req);
}
项目:Poseidon    文件:PoseidonServlet.java   
private void handleFileUpload(PoseidonRequest request, HttpServletRequest httpRequest) throws IOException {
    // If uploaded file size is more than 10KB, will be stored in disk
    DiskFileItemFactory factory = new DiskFileItemFactory();
    File repository = new File(FILE_UPLOAD_TMP_DIR);
    if (repository.exists()) {
        factory.setRepository(repository);
    }

    // Currently we don't impose max file size at container layer. Apps can impose it by checking FileItem
    // Apps also have to delete tmp file explicitly (if at all it went to disk)
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> fileItems = null;
    try {
        fileItems = upload.parseRequest(httpRequest);
    } catch (FileUploadException e) {
        throw new IOException(e);
    }
    for (FileItem fileItem : fileItems) {
        String name = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            request.setAttribute(name, new String[] { fileItem.getString() });
        } else {
            request.setAttribute(name, fileItem);
        }
    }
}
项目:Wilma    文件:MultiPartFormUploadServlet.java   
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    if (!isMultipartContent) {
        out.println("You are not trying to upload");
    } else {
        try {
            List<FileItem> fields = upload.parseRequest(request);
            String msg = filesParser.parseMultiPartFiles(fields);
            LOGGER.info(urlAccessLogMessageAssembler.assembleMessage(request, msg));
            out.write(msg);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("File uploading failed! cause: " + e.getMessage());
            LOGGER.info(urlAccessLogMessageAssembler.assembleMessage(request, e.getMessage()), e);
        }
    }
}
项目:ExilityCore-5.0.0    文件:XLSHandler.java   
/**
 * This method returns FileItem handler out of file field in HTTP request
 * 
 * @param req
 * @return FileItem
 * @throws IOException
 * @throws FileUploadException
 */
@SuppressWarnings("unchecked")
public static FileItem getFileItem(HttpServletRequest req)
        throws IOException, FileUploadException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    /*
     * we can increase the in memory size to hold the file data but its
     * inefficient so ignoring to factory.setSizeThreshold(20*1024);
     */
    ServletFileUpload sFileUpload = new ServletFileUpload(factory);
    List<FileItem> items = sFileUpload.parseRequest(req);
    for (FileItem item : items) {
        if (!item.isFormField()) {
            return item;
        }
    }

    throw new FileUploadException("File field not found");

}
项目:ExilityCore-5.0.0    文件:HttpUtils.java   
/***
 * Simplest way of handling files that are uploaded from form. Just put them
 * as name-value pair into service data. This is useful ONLY if the files
 * are reasonably small.
 * 
 * @param req
 * @param data
 *            data in which
 */
public void simpleExtract(HttpServletRequest req, ServiceData data) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        /**
         * ServerFileUpload still deals with raw types. we have to have
         * workaround that
         */
        List<?> list = upload.parseRequest(req);
        if (list != null) {
            for (Object item : list) {
                if (item instanceof FileItem) {
                    FileItem fileItem = (FileItem) item;
                    data.addValue(fileItem.getFieldName(),
                            fileItem.getString());
                } else {
                    Spit.out("Servlet Upload retruned an item that is not a FileItem. Ignorinig that");
                }
            }
        }
    } catch (FileUploadException e) {
        Spit.out(e);
        data.addError("Error while parsing form data. " + e.getMessage());
    }
}
项目:jpublish    文件:ProxyServlet.java   
/**
 * Performs an HTTP POST request
 *
 * @param httpServletRequest  The {@link HttpServletRequest} object passed
 *                            in by the servlet engine representing the
 *                            client request to be proxied
 * @param httpServletResponse The {@link HttpServletResponse} object by which
 *                            we can send a proxied response to the client
 */
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    // Create a standard POST request
    String contentType = httpServletRequest.getContentType();
    String destinationUrl = this.getProxyURL(httpServletRequest);
    debug("POST Request URL: " + httpServletRequest.getRequestURL(),
            "    Content Type: " + contentType,
            " Destination URL: " + destinationUrl);
    PostMethod postMethodProxyRequest = new PostMethod(destinationUrl);
    // Forward the request headers
    setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest);
    setProxyRequestCookies(httpServletRequest, postMethodProxyRequest);
    // Check if this is a mulitpart (file upload) POST
    if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
        this.handleMultipartPost(postMethodProxyRequest, httpServletRequest);
    } else {
        if (contentType == null || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equals(contentType)) {
            this.handleStandardPost(postMethodProxyRequest, httpServletRequest);
        } else {
            this.handleContentPost(postMethodProxyRequest, httpServletRequest);
        }
    }
    // Execute the proxy request
    this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse);
}
项目:azkaban-customization    文件:MultipartParser.java   
@SuppressWarnings("unchecked")
public Map<String, Object> parseMultipart(HttpServletRequest request)
        throws IOException, ServletException {
    ServletFileUpload upload = new ServletFileUpload(_uploadItemFactory);
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    Map<String, Object> params = new HashMap<String, Object>();
    for (FileItem item : items) {
        if (item.isFormField())
            params.put(item.getFieldName(), item.getString());
        else
            params.put(item.getFieldName(), item);
    }
    return params;
}
项目:TupiFS-Agent    文件:Connector.java   
/**
 * Performs an HTTP POST request
 * @param request The {@link HttpServletRequest} object passed
 *                            in by the servlet engine representing the
 *                            client request to be proxied
 * @param response The {@link HttpServletResponse} object by which
 *                             we can send a proxied response to the client 
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {

    // Create a standard POST request
    HttpRequestBase proxyRequest = new HttpPost(getProxyURL(request));

    // Forward the request headers
    proxyRequest = setProxyRequestHeaders(request, proxyRequest);

    HttpPost proxyRequestPost = (HttpPost) proxyRequest;

    // Check if this is a mulitpart (file upload) POST
    if (ServletFileUpload.isMultipartContent(request)) {
        proxyRequestPost = handleMultipartPost(proxyRequestPost, request);
    } else {
        proxyRequestPost = handleStandardPost(proxyRequestPost, request);
    }

    // Execute the proxy request
    executeProxyRequest(proxyRequestPost, request, response);
}
项目:OLE-INST    文件:DocumentServlet.java   
/**
 * @param request
 * @param response
 * @return docAction (add or delete)
 * @throws ServletException
 */
protected List<FileItem> getMultiPartFileItems(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    List<FileItem> items = null;
    try {
        if (isMultipart) {
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
            items = uploadHandler.parseRequest(request);
        }
    } catch (Exception ex) {
        LOG.error("Error in getting the Reading the File:", ex);
    }
    return items;
}
项目:OLE-INST    文件:DocumentServlet.java   
private ArrayList<File> extractBagFilesFromRequest(HttpServletRequest req, HttpServletResponse res)
        throws Exception {
    File targetDir = null;
    try {
        File file = null;
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
        Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator();
        while (items.hasNext()) {
            FileItem item = (FileItem) items.next();
            file = new File(FileUtils.getTempDirectory(), item.getName());
            item.write(file);
        }
        targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), null);
        LOG.info("extractedBagFileLocation " + targetDir);
    } catch (IOException e) {
        LOG.error("IOException", e);
        sendResponseBag(res, e.getMessage(), "failure");
    } catch (FormatHelper.UnknownFormatException unknownFormatException) {
        LOG.error("unknownFormatException", unknownFormatException);
        sendResponseBag(res, unknownFormatException.getMessage(), "failure");
    }
    return compressUtils.getAllFilesList(targetDir);
}