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

The following are top voted examples for showing how to use org.apache.commons.fileupload.servlet.ServletFileUpload. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: iBase4J-Common   File: UploadUtil.java   View source code 8 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
 
Example 2
Project: scaffold   File: Uploader.java   View source code 8 votes vote down vote up
/**
 * 文件上传处理类
 *
 * @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);
}
 
Example 3
Project: automat   File: UploadUtil.java   View source code 7 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 4
Project: mumu   File: UploadUtil.java   View source code 7 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 5
Project: iBase4J   File: UploadUtil.java   View source code 7 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
 
Example 6
Project: JAVA-   File: UploadUtil.java   View source code 7 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 7
Project: mumu-core   File: UploadUtil.java   View source code 7 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 8
Project: osframe   File: UploadUtil.java   View source code 7 votes vote down vote up
/** 获取所有文本域 */
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;
}
 
Example 9
Project: xslweb   File: RequestSerializer.java   View source code 7 votes vote down vote up
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;
}
 
Example 10
Project: jawn   File: JawnServletContext.java   View source code 7 votes vote down vote up
/**
 * 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();
}
 
Example 11
Project: OLE-INST   File: DocumentResources.java   View source code 7 votes vote down vote up
private ArrayList<File> extractBagFilesFromRequest(@Context HttpServletRequest req,
                                                   @Context 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();
            LOG.info("item Name = " + item.getName() + " ; content type = " + item.getContentType());
            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);
}
 
Example 12
Project: Breakpoint-http   File: IndexController.java   View source code 6 votes vote down vote up
/**
 * 上传文件
 *
 * @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("上传成功。");
}
 
Example 13
Project: urule   File: FrameServletHandler.java   View source code 6 votes vote down vote up
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");
}
 
Example 14
Project: urule   File: PackageServletHandler.java   View source code 6 votes vote down vote up
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);
}
 
Example 15
Project: convertigo-engine   File: UploadService.java   View source code 6 votes vote down vote up
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);
	}
}
 
Example 16
Project: xmall   File: QiniuUtil.java   View source code 6 votes vote down vote up
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";
}
 
Example 17
Project: oryx2   File: AbstractOryxResource.java   View source code 6 votes vote down vote up
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());
  }
}
 
Example 18
Project: carbon   File: MultipartFormKeyValueRequestMapper.java   View source code 6 votes vote down vote up
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
    ));
}
 
Example 19
Project: openbravo-brazil   File: VariablesBase.java   View source code 6 votes vote down vote up
/**
 * 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();
      }
    }
  }
}
 
Example 20
Project: webframework   File: SimpleRequestObject.java   View source code 6 votes vote down vote up
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));
		}
	}
}
 
Example 21
Project: giiwa   File: Model.java   View source code 6 votes vote down vote up
/**
 * 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();
	}

}
 
Example 22
Project: simbest-cores   File: CustomMultipartResolver.java   View source code 6 votes vote down vote up
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;
}
 
Example 23
Project: bisis-v4   File: FileManagerServlet.java   View source code 6 votes vote down vote up
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);
    }
  }
}
 
Example 24
Project: azkaban   File: MultipartParser.java   View source code 6 votes vote down vote up
@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;
}
 
Example 25
Project: webwheel   File: JsonResult.java   View source code 6 votes vote down vote up
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);
}
 
Example 26
Project: aet   File: SuiteServlet.java   View source code 6 votes vote down vote up
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;
}
 
Example 27
Project: nio-multipart   File: MultipartController.java   View source code 6 votes vote down vote up
/**
 * <p> Example of parsing the multipart request using commons file upload. In this case the parsing happens in blocking io.
 *
 * @param request The {@code HttpServletRequest}
 * @return The {@code VerificationItems}
 * @throws Exception if an exception happens during the parsing
 */
@RequestMapping(value = "/blockingio/fileupload/multipart", method = RequestMethod.POST)
public @ResponseBody VerificationItems blockingIoMultipart(final HttpServletRequest request) throws Exception {

    assertRequestIsMultipart(request);

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

    final VerificationItems verificationItems = new VerificationItems();
    Metadata metadata = null;
    while (fileItemIterator.hasNext()){
        FileItemStream fileItemStream = fileItemIterator.next();
        if (METADATA_FIELD_NAME.equals(fileItemStream.getFieldName())){
            if (metadata != null){
                throw new IllegalStateException("Found more than one metadata field");
            }
            metadata = unmarshalMetadata(fileItemStream.openStream());
        }else {
            VerificationItem verificationItem = buildVerificationItem(fileItemStream.openStream(), fileItemStream.getFieldName(), fileItemStream.isFormField());
            verificationItems.getVerificationItems().add(verificationItem);
        }
    }
    processVerificationItems(verificationItems, metadata, false, request.getHeader(VERIFICATION_CONTROL_HEADER_NAME));
    return verificationItems;
}
 
Example 28
Project: kc-rice   File: RequestParser.java   View source code 6 votes vote down vote up
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;
}
 
Example 29
Project: FOXopen   File: MultipartUploadReader.java   View source code 6 votes vote down vote up
/**
 * 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());
  }
}
 
Example 30
Project: FOXopen   File: UploadServlet.java   View source code 6 votes vote down vote up
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);
  }
 
Example 31
Project: jeecms6   File: SnapScreenServlet.java   View source code 6 votes vote down vote up
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;
}
 
Example 32
Project: search   File: SolrRequestParsers.java   View source code 6 votes vote down vote up
@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);
}
 
Example 33
Project: Poseidon   File: PoseidonServlet.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 34
Project: Wilma   File: MultiPartFormUploadServlet.java   View source code 6 votes vote down vote up
@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);
        }
    }
}
 
Example 35
Project: ExilityCore-5.0.0   File: XLSHandler.java   View source code 6 votes vote down vote up
/**
 * 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");

}
 
Example 36
Project: ExilityCore-5.0.0   File: HttpUtils.java   View source code 6 votes vote down vote up
/***
 * 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());
	}
}
 
Example 37
Project: jpublish   File: ProxyServlet.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 38
Project: azkaban-customization   File: MultipartParser.java   View source code 6 votes vote down vote up
@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;
}
 
Example 39
Project: TupiFS-Agent   File: Connector.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 40
Project: OLE-INST   File: DocumentServlet.java   View source code 6 votes vote down vote up
/**
 * @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;
}