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

The following are top voted examples for showing how to use org.apache.commons.fileupload.FileUploadException. 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: JAVA-   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 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: 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 7
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 8
Project: hermes   File: PartnershipPageletAdaptor.java   View source code 7 votes vote down vote up
public Hashtable getHashtable(HttpServletRequest request)
        throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}
 
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: 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 12
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 13
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 14
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 15
Project: hermes   File: PartnershipPageletAdaptor.java   View source code 6 votes vote down vote up
public Hashtable getHashtable(HttpServletRequest request)
    throws FileUploadException, IOException {
	Hashtable ht = new Hashtable();
	DiskFileUpload upload = new DiskFileUpload();
	List fileItems = upload.parseRequest(request);
	Iterator iter = fileItems.iterator();
	while (iter.hasNext()) {
	    FileItem item = (FileItem) iter.next();
	    if (item.isFormField()) {
	        ht.put(item.getFieldName(), item.getString());
	    } else {
	        if (item.getName().equals("")) {
	            //ht.put(item.getFieldName(), null);
	        } else if (item.getSize() == 0) {
	            //ht.put(item.getFieldName(), null);
	        } else {
	            ht.put(item.getFieldName(), item.getInputStream());
	        }
	    }
	}
	return ht;
}
 
Example 16
Project: hermes   File: PartnershipPageletAdaptor.java   View source code 6 votes vote down vote up
public Hashtable getHashtable(HttpServletRequest request)
        throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}
 
Example 17
Project: hermes   File: PartnershipPageletAdaptor.java   View source code 6 votes vote down vote up
public Hashtable getHashtable(HttpServletRequest request)
        throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}
 
Example 18
Project: helicalinsight   File: MultipartFilter.java   View source code 6 votes vote down vote up
/**
 * Process multipart request item as file field. The name and FileItem
 * object of each file field will be added as attribute of the given
 * HttpServletRequest. If a FileUploadException has occurred when the file
 * size has exceeded the maximum file size, then the FileUploadException
 * will be added as attribute value instead of the FileItem object.
 *
 * @param fileField The file field to be processed.
 * @param request   The involved HttpServletRequest.
 */
private void processFileField(FileItem fileField, HttpServletRequest request) {
    if (fileField.getName().length() <= 0) {
        // No file uploaded.
        request.setAttribute(fileField.getFieldName(), null);
    } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
        // File size exceeds maximum file size.
        request.setAttribute(fileField.getFieldName(), new FileUploadException("File size " +
                "exceeds maximum file size of " + maxFileSize + " bytes."));
        // Immediately delete temporary file to free up memory and/or disk
        // space.
        fileField.delete();
    } else {
        // File uploaded with good size.
        request.setAttribute(fileField.getFieldName(), fileField);
    }
}
 
Example 19
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 20
Project: tern   File: MultiPartEnabledRequest.java   View source code 6 votes vote down vote up
public MultiPartEnabledRequest(HttpServletRequest req) 
{
    super(req);
    this.multipart = FileUpload.isMultipartContent(req);
    if (multipart) 
    {
      try 
      {
        readHttpParams(req);
      }
      catch (FileUploadException e) 
      {
    	  Trace.write(Trace.Error,e, "MultiPartEnabledRequest");
          e.printStackTrace();
      }
    }
  }
 
Example 21
Project: communote-server   File: AttachmentResourceHandler.java   View source code 6 votes vote down vote up
/**
 * extracts attachments from the http request.
 *
 * @param httpRequest
 *            request containing attachments DefaultMultipartHttpServletRequest is supported
 * @param request
 *            {@link Request}
 * @return ids of extracted attachments
 * @throws IOException
 *             throws exception if problems during attachments accessing occurred
 * @throws FileUploadException
 *             Exception.
 * @throws AttachmentIsEmptyException
 *             Thrown, when the attachment is of zero size.
 * @throws AuthorizationException
 *             in case there is no authenticated user
 */
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
        Request request) throws FileUploadException, IOException,
        AttachmentIsEmptyException, AuthorizationException {
    List<AttachmentResource> result = new ArrayList<>();
    if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
        FileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
        for (FileItem file : items) {
            if (!file.isFormField()) {
                AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
                        AttachmentStatus.UPLOADED);
                AttachmentResourceHelper.assertAttachmentSize(file.getContentType(),
                        file.getSize(), false);
                attachmentTo.setMetadata(new ContentMetadata());
                attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
                attachmentTo.getMetadata().setContentSize(file.getSize());
                result.add(persistAttachment(request, attachmentTo));
            }
        }
    }
    return result;
}
 
Example 22
Project: communote-server   File: AttachmentResourceHandler.java   View source code 6 votes vote down vote up
/**
 * extracts attachments from the http request.
 *
 * @param httpRequest
 *            request containing attachments DefaultMultipartHttpServletRequest is supported
 * @param request
 *            {@link Request}
 * @return ids of extracted attachments
 * @throws MaxLengthReachedException
 *             attachment size is to large
 * @throws IOException
 *             throws exception if problems during attachments accessing occurred
 * @throws FileUploadException
 *             Exception.
 * @throws AttachmentIsEmptyException
 *             Thrown, when the attachment is of zero size.
 * @throws AuthorizationException
 *             in case there is no authenticated user
 */
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
        Request request) throws MaxLengthReachedException, FileUploadException, IOException,
        AttachmentIsEmptyException, AuthorizationException {
    List<AttachmentResource> result = new ArrayList<AttachmentResource>();
    if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
        FileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
        for (FileItem file : items) {
            if (!file.isFormField()) {
                AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
                        AttachmentStatus.UPLOADED);
                AttachmentResourceHelper.assertAttachmentSize(file.getContentType(),
                        file.getSize(), false);
                attachmentTo.setMetadata(new ContentMetadata());
                attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
                attachmentTo.getMetadata().setContentSize(file.getSize());
                result.add(persistAttachment(request, attachmentTo));
            }
        }
    }
    return result;
}
 
Example 23
Project: communote-server   File: AttachmentResourceHandler.java   View source code 6 votes vote down vote up
/**
 * extracts attachments from the http request.
 *
 * @param httpRequest
 *            request containing attachments DefaultMultipartHttpServletRequest is supported
 * @param request
 *            {@link Request}
 * @return ids of extracted attachments
 * @throws MaxLengthReachedException
 *             attachment size is to large
 * @throws IOException
 *             throws exception if problems during attachments accessing occurred
 * @throws FileUploadException
 *             Exception.
 * @throws AuthorizationException
 *             in case there is no authenticated user
 */
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
        Request request) throws MaxLengthReachedException, FileUploadException, IOException,
        AuthorizationException {
    List<AttachmentResource> result = new ArrayList<AttachmentResource>();
    if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
        FileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
        for (FileItem file : items) {
            if (!file.isFormField()) {
                AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
                        AttachmentStatus.UPLOADED);
                AttachmentResourceHelper.assertAttachmentSize(file.getContentType(),
                        file.getSize(), false);
                attachmentTo.setMetadata(new ContentMetadata());
                attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
                attachmentTo.getMetadata().setContentSize(file.getSize());
                result.add(persistAttachment(request, attachmentTo));
            }
        }
    }
    return result;
}
 
Example 24
Project: communote-server   File: AttachmentResourceHandler.java   View source code 6 votes vote down vote up
/**
 * extracts attachments from the http request.
 *
 * @param httpRequest
 *            request containing attachments DefaultMultipartHttpServletRequest is supported
 * @param request
 *            {@link Request}
 * @return ids of extracted attachments
 * @throws MaxLengthReachedException
 *             attachment size is to large
 * @throws IOException
 *             throws exception if problems during attachments accessing occurred
 * @throws FileUploadException
 *             Exception.
 * @throws AuthorizationException
 *             in case there is no authenticated user
 */
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
        Request request) throws MaxLengthReachedException, FileUploadException, IOException,
        AuthorizationException {
    List<AttachmentResource> result = new ArrayList<AttachmentResource>();
    if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
        FileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
        for (FileItem file : items) {
            if (!file.isFormField()) {
                AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
                        AttachmentStatus.UPLOADED);
                AttachmentResourceHelper.checkAttachmentSize(file);
                attachmentTo.setMetadata(new ContentMetadata());
                attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
                attachmentTo.getMetadata().setContentSize(file.getSize());
                result.add(persistAttachment(request, attachmentTo));
            }
        }
    }
    return result;
}
 
Example 25
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 26
Project: prudence   File: LazyInitializationFile.java   View source code 6 votes vote down vote up
@Override
protected void initialize()
{
	if( ( request.getMethod().equals( Method.POST ) || request.getMethod().equals( Method.PUT ) ) && request.isEntityAvailable() && request.getEntity().getMediaType().includes( MediaType.MULTIPART_FORM_DATA ) )
	{
		try
		{
			for( FileItem fileItem : fileUpload.parseRequest( request ) )
			{
				if( fileItem.isFormField() )
					formFields.put( fileItem.getFieldName(), fileItem.getString() );
				else
					map.put( fileItem.getFieldName(), Collections.unmodifiableMap( createFileItemMap( fileItem ) ) );
			}
		}
		catch( FileUploadException x )
		{
			x.printStackTrace();
		}
	}
}
 
Example 27
Project: Express4J   File: FileUploadHelper.java   View source code 6 votes vote down vote up
/**
 * 读取表单中的参数
 * eg:普通文本或文件
 * @param request
 * @return
 */
public static void createMultipartForm(RequestParam params ,HttpServletRequest request){
    //Parse the request
    try {
        List<FileItem> items = fileUpload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                processFormField(params,item);
            } else {
                processUploadedFile(params,item);
            }
        }
    } catch (FileUploadException e) {
        logger.error("File Upload Failure :" +e );
        e.printStackTrace();
    }
}
 
Example 28
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 29
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 30
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 31
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 32
Project: RestServices   File: MicroflowService.java   View source code 6 votes vote down vote up
private void parseMultipartData(RestServiceRequest rsr, IMendixObject argO,
		JSONObject data) throws IOException, FileUploadException {
	boolean hasFile = false;
	
	for(FileItemIterator iter = servletFileUpload.getItemIterator(rsr.request); iter.hasNext();) {
		FileItemStream item = iter.next();
		if (!item.isFormField()){ //This is the file(?!)
			if (!isFileSource) {
				RestServices.LOGPUBLISH.warn("Received request with binary data but input argument isn't a filedocument. Skipping. At: " + rsr.request.getRequestURL().toString());
				continue;
			}
			if (hasFile)
				RestServices.LOGPUBLISH.warn("Received request with multiple files. Only one is supported. At: " + rsr.request.getRequestURL().toString());
			hasFile = true;
			Core.storeFileDocumentContent(rsr.getContext(), argO, determineFileName(item), item.openStream());
		}
		else
			data.put(item.getFieldName(), IOUtils.toString(item.openStream()));
	}
}
 
Example 33
Project: community-edition-old   File: JBPMDeployProcessServlet.java   View source code 6 votes vote down vote up
/**
 * Retrieve the JBPM Process Designer deployment archive from the request
 * 
 * @param request  the request
 * @return  the input stream onto the deployment archive
 * @throws WorkflowException
 * @throws FileUploadException
 * @throws IOException
 */
private InputStream getDeploymentArchive(HttpServletRequest request)
    throws FileUploadException, IOException
{
    if (!FileUpload.isMultipartContent(request))
    {
        throw new FileUploadException("Not a multipart request");
    }
    
    GPDUpload fileUpload = new GPDUpload();
    List list = fileUpload.parseRequest(request);
    Iterator iterator = list.iterator();
    if (!iterator.hasNext())
    {
        throw new FileUploadException("No process file in the request");
    }
 
    FileItem fileItem = (FileItem) iterator.next();
    if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1)
    {
        throw new FileUploadException("Not a process archive");
    }
    
    return fileItem.getInputStream();
}
 
Example 34
Project: signalk-server-java   File: UploadProcessor.java   View source code 6 votes vote down vote up
private void processUpload(Exchange exchange) throws Exception {
	logger.debug("Begin import:"+ exchange.getIn().getHeaders());
	if(exchange.getIn().getBody()!=null){
		logger.debug("Body class:"+ exchange.getIn().getBody().getClass());
	}else{
		logger.debug("Body class is null");
	}
	//logger.debug("Begin import:"+ exchange.getIn().getBody());
	MediaType mediaType = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class);
	InputRepresentation representation = new InputRepresentation((InputStream) exchange.getIn().getBody(), mediaType);
	logger.debug("Found MIME:"+ mediaType+", length:"+exchange.getIn().getHeader(Exchange.CONTENT_LENGTH, Integer.class));
	//make a reply
	Json reply = Json.read("{\"files\": []}");
	Json files = reply.at("files");
	
	try {
		List<FileItem> items = new RestletFileUpload(new DiskFileItemFactory()).parseRepresentation(representation);
		logger.debug("Begin import files:"+items);
		for (FileItem item : items) {
			if (!item.isFormField()) {
				InputStream inputStream = item.getInputStream();
				
				Path destination = Paths.get(Util.getConfigProperty(STATIC_DIR)+Util.getConfigProperty(MAP_DIR)+item.getName());
				logger.debug("Save import file:"+destination);
				long len = Files.copy(inputStream, destination, StandardCopyOption.REPLACE_EXISTING);
				Json f = Json.object();
				f.set("name",item.getName());
				f.set("size",len);
				files.add(f);
				install(destination);
			}
		}
	} catch (FileUploadException | IOException e) {
		logger.error(e.getMessage(),e);
	}
	exchange.getIn().setBody(reply);
}
 
Example 35
Project: domaintest   File: EmailApiModule.java   View source code 6 votes vote down vote up
/**
 * 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.
}
 
Example 36
Project: sigmah   File: ImportServlet.java   View source code 6 votes vote down vote up
/**
 * Store the uploaded file on the disk and return the identifier of the
 * file to the user.
 * 
 * @param request Http request.
 * @param response Http response.
 * @param context Execution context.
 * @throws FileUploadException If an error occured while reading the http request.
 * @throws IOException If the file could not be written on the server.
 */
public void storeFile(final HttpServletRequest request, final HttpServletResponse response, final ServletExecutionContext context) throws FileUploadException, IOException {
	final HashMap<String, String> properties = new HashMap<String, String>();
	final byte[] data;
	
	try {
		data = readFileAndProperties(request, properties);
		
	} catch (FileUploadException | IOException ex) {
		LOG.error("Error while receiving a file containing values.", ex);
		throw ex;
	}

	if (data != null) {
		// A file has been received
		final String uniqueFileId = FileServlet.generateUniqueName();
		final long length = fileStorageProvider.copy(new ByteArrayInputStream(data), uniqueFileId, StandardCopyOption.REPLACE_EXISTING);
		
		if(length > 0) {
			response.setContentType("text/html");
			response.getWriter().write(uniqueFileId);
		}
	}
}
 
Example 37
Project: sigmah   File: MultipartRequest.java   View source code 6 votes vote down vote up
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());
		}
	}
}
 
Example 38
Project: stratos   File: AbstractFileUploadExecutor.java   View source code 6 votes vote down vote up
protected void checkServiceFileExtensionValidity(String fileExtension,
                                                 String[] allowedExtensions)
        throws FileUploadException {
    boolean isExtensionValid = false;
    StringBuffer allowedExtensionsStr = new StringBuffer();
    for (String allowedExtension : allowedExtensions) {
        allowedExtensionsStr.append(allowedExtension).append(",");
        if (fileExtension.endsWith(allowedExtension)) {
            isExtensionValid = true;
            break;
        }
    }
    if (!isExtensionValid) {
        throw new FileUploadException(" Illegal file type." +
                                      " Allowed file extensions are " + allowedExtensionsStr);
    }
}
 
Example 39
Project: socom   File: SocomRequest.java   View source code 6 votes vote down vote up
public Map<String, FileItem> getMultipartContent() throws FileUploadException, IllegalAccessException {

		if (!ServletFileUpload.isMultipartContent(request))
			throw new IllegalAccessException();

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);

		Map<String, FileItem> result = new HashMap<String, FileItem>();

		@SuppressWarnings("unchecked")
		List<FileItem> items = upload.parseRequest(request);
		for (FileItem fi : items) {
			result.put(fi.getFieldName(), fi);
		}
		return result;
	}
 
Example 40
Project: gen-server-http-listener   File: RequestFileHandlingUtilities.java   View source code 6 votes vote down vote up
/**
 * Handles a file contained in the specified {@code request}. If you use
 * FileUpload, please make sure to add the needed dependencies, i.e.
 * {@code commons-fileupload} and {@code servlet-api} (later will be removed
 * in a newer version of the {@code commons-fileupload}.
 * 
 * @param request
 *            the request to handle the file upload from
 * @param factory
 *            the {@code FileItemFactory} used to handle the request
 * 
 * @return the {@code List} of loaded files
 * 
 * @throws FileUploadException
 *             if the file upload fails
 */
public static List<FileItem> handleFileUpload(final HttpRequest request,
		final FileItemFactory factory) throws FileUploadException {
	final List<FileItem> items;
	if (request instanceof HttpEntityEnclosingRequest
			&& "POST".equals(request.getRequestLine().getMethod())) {

		// create the ServletFileUpload
		final FileUpload upload = new FileUpload(factory);

		final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
		items = upload.parseRequest(new RequestWrapper(entityRequest));
	} else {
		items = new ArrayList<FileItem>();
	}

	return items;
}