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

The following examples show how to use org.apache.commons.fileupload.servlet.ServletFileUpload. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Wrap a request with an object aware of the current repository and application defaults.
 *
 * @param repository currently connected repository
 * @param request    current request
 * @param defaults   application default parameter values
 * @throws RepositoryException if there is an issue retrieving the parameter map
 * @throws IOException         if there is an issue retrieving the parameter map
 * @throws FileUploadException if there is an issue retrieving the parameter map
 */
public WorkbenchRequest(Repository repository, HttpServletRequest request, Map<String, String> defaults)
		throws RepositoryException, IOException, FileUploadException {
	super(request);
	this.defaults = defaults;
	this.decoder = new ValueDecoder(repository,
			(repository == null) ? SimpleValueFactory.getInstance() : repository.getValueFactory());
	String url = request.getRequestURL().toString();
	if (ServletFileUpload.isMultipartContent(this)) {
		parameters = getMultipartParameterMap();
	} else if (request.getQueryString() == null && url.contains(";")) {
		parameters = getUrlParameterMap(url);
	}
}
 
Example 2
Source Project: Poseidon   Source File: PoseidonServlet.java    License: Apache License 2.0 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 3
Source Project: BigDataPlatform   Source File: QiniuUtil.java    License: GNU General Public License v3.0 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 4
Source Project: rebuild   Source File: FileUploader.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 读取上传的文件列表
 * 
 * @param request
 * @return
 * @throws Exception
 */
private static List<FileItem> parseFileItem(HttpServletRequest request) throws Exception {
	if (!ServletFileUpload.isMultipartContent(request)) {
		return Collections.emptyList();
	}
	
	ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
	List<FileItem> files = null;
	try {
		files = upload.parseRequest(request);
	} catch (Exception ex) {
		if (ex instanceof IOException || ex.getCause() instanceof IOException) {
			LOG.warn("传输意外中断", ex);
			return Collections.emptyList();
		}
		throw ex;
	}
	
	if (files == null || files.isEmpty()) {
		return Collections.emptyList();
	}
	return files;
}
 
Example 5
/**
 * @see MultiPartManager#getParts(cloud.piranha.webapp.api.WebApplication, cloud.piranha.webapp.api.WebApplicationRequest) 
 */
@Override
public Collection<Part> getParts(WebApplication webApplication,
        WebApplicationRequest request) throws ServletException {

    Collection<Part> parts = new ArrayList<>();
    if (LOGGER.isLoggable(FINE)) {
        LOGGER.log(FINE, "Getting parts for request: {0}", request);
    }
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            ServletFileUpload upload = setupFileUpload(webApplication);
            List<FileItem> items = upload.parseRequest(request);
            items.forEach((item) -> {
                parts.add(new ApacheMultiPart(item));
            });
        } catch (FileUploadException fue) {
        }
    } else {
        throw new ServletException("Not a multipart/form-data request");
    }
    return parts;
}
 
Example 6
Source Project: openrasp-testcases   Source File: Multipart_mysql.java    License: MIT License 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        String id = null;
        if (req.getMethod().equals("POST")) {
            if (ServletFileUpload.isMultipartContent(req)) {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(req);
                for (FileItem item : items) {
                    if (item.isFormField() && item.getFieldName().equals("id")) {
                        id = item.getString();
                        break;
                    }
                }
            }
        }
        if (id == null) {
            id = "1";
        }
        String result = Mysql.runQuery(id);
        resp.getWriter().println(result);
    } catch (Exception e) {
        resp.getWriter().println(e);
    }
}
 
Example 7
Source Project: openrasp-testcases   Source File: FileUpload.java    License: MIT License 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        String method = req.getMethod();
        if ("POST".equals(method)){
            boolean isMultipart = ServletFileUpload.isMultipartContent(req);
            if (isMultipart) {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(req);
                for (FileItem item : items) {
                    String content = new String(item.get());
                    resp.getWriter().println(content);
                }
            }
        }
    } catch (Exception e) {
        resp.getWriter().println(e);
    }
}
 
Example 8
Source Project: urule   Source File: FrameServletHandler.java    License: Apache License 2.0 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 9
Source Project: urule   Source File: PackageServletHandler.java    License: Apache License 2.0 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 10
Source Project: mumu   Source File: UploadUtil.java    License: Apache License 2.0 6 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 11
private FileItem handleMultipartForm(HttpServletRequest request) throws Exception {

		// Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

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

		// Parse the request
		List fileItems = upload.parseRequest(request);
		Iterator iter = fileItems.iterator();

		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			if (item.isFormField()) {
				String name = item.getFieldName();
				String value = item.getString();
			} else {
				return item;
			}
		}
		return null;
	}
 
Example 12
Source Project: rice   Source File: RequestParser.java    License: Educational Community License v2.0 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 13
/**
 * Handle multipart form.
 * 
 * @param request        the request
 * @param requestContext the request context
 * 
 * @throws Exception the exception
 */
private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) throws Exception {
	SourceBean serviceRequest = requestContext.getServiceRequest();

	// Create a factory for disk-based file items
	FileItemFactory factory = new DiskFileItemFactory();

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

	// Parse the request
	List fileItems = upload.parseRequest(request);
	Iterator iter = fileItems.iterator();
	while (iter.hasNext()) {
		FileItem item = (FileItem) iter.next();

		if (item.isFormField()) {
			String name = item.getFieldName();
			String value = item.getString(request.getCharacterEncoding());
			serviceRequest.setAttribute(name, value);
		} else {
			processFileField(item, requestContext);
		}
	}
}
 
Example 14
private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) 
	throws Exception{
	SourceBean serviceRequest = requestContext.getServiceRequest();
	
	// Create a factory for disk-based file items
	FileItemFactory factory = new DiskFileItemFactory();
	
    // Create a new file upload handler
	ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();
            serviceRequest.setAttribute(name, value);
        } else {
            processFileField(item, requestContext);
        }
    }
}
 
Example 15
private Map<String, String> getMultipartParameterMap()
		throws RepositoryException, IOException, FileUploadException {
	Map<String, String> parameters = new HashMap<>();
	ServletFileUpload upload = new ServletFileUpload();
	FileItemIterator iter = upload.getItemIterator(this);
	while (iter.hasNext()) {
		FileItemStream item = iter.next();
		String name = item.getFieldName();
		if ("content".equals(name)) {
			content = item.openStream();
			contentFileName = item.getName();
			break;
		} else {
			parameters.put(name, firstLine(item));
		}
	}
	return parameters;
}
 
Example 16
@PostMapping
protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception {

    String username = securityService.getCurrentUsername(request);

    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }

    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    // Look for file items.
    for (FileItem item : items) {
        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();

            if (StringUtils.isNotBlank(fileName) && data.length > 0) {
                createAvatar(fileName, data, username, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload personal image. No file specified.");
            }
            break;
        }
    }

    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    return new ModelAndView("avatarUploadResult","model",map);
}
 
Example 17
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload() {
		@Override
		public List<FileItem> parseRequest(HttpServletRequest request) {
			if (request instanceof MultipartHttpServletRequest) {
				throw new IllegalStateException("Already a multipart request");
			}
			List<FileItem> fileItems = new ArrayList<>();
			MockFileItem fileItem1 = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem1x = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem2 = new MockFileItem(
				"field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2");
			MockFileItem fileItem2x = new MockFileItem(
				"field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2");
			MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3");
			MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4");
			MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5");
			fileItems.add(fileItem1);
			fileItems.add(fileItem1x);
			fileItems.add(fileItem2);
			fileItems.add(fileItem2x);
			fileItems.add(fileItem3);
			fileItems.add(fileItem4);
			fileItems.add(fileItem5);
			return fileItems;
		}
	};
}
 
Example 18
Source Project: ttt   Source File: CheckerServlet.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void doCheck(RequestState state) throws ServletException, IOException {
    try {
        if (!ServletFileUpload.isMultipartContent(state.request))
            processQueryRequest(state);
        else
            processNonQueryRequest(state);
        processCheck(state);
        processResponse(state);
    } finally {
        state.reset();
    }
}
 
Example 19
Source Project: smart-framework   Source File: UploadHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 初始化
 */
public static void init(ServletContext servletContext) {
    // 获取一个临时目录(使用 Tomcat 的 work 目录)
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    // 创建 FileUpload 对象
    fileUpload = new ServletFileUpload(new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository));
    // 设置上传限制
    int uploadLimit = FrameworkConstant.UPLOAD_LIMIT;
    if (uploadLimit != 0) {
        fileUpload.setFileSizeMax(uploadLimit * 1024 * 1024); // 单位为 M
    }
}
 
Example 20
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload() {
		@Override
		public List<FileItem> parseRequest(HttpServletRequest request) {
			if (request instanceof MultipartHttpServletRequest) {
				throw new IllegalStateException("Already a multipart request");
			}
			List<FileItem> fileItems = new ArrayList<>();
			MockFileItem fileItem1 = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem1x = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem2 = new MockFileItem(
				"field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2");
			MockFileItem fileItem2x = new MockFileItem(
				"field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2");
			MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3");
			MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4");
			MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5");
			fileItems.add(fileItem1);
			fileItems.add(fileItem1x);
			fileItems.add(fileItem2);
			fileItems.add(fileItem2x);
			fileItems.add(fileItem3);
			fileItems.add(fileItem4);
			fileItems.add(fileItem5);
			return fileItems;
		}
	};
}
 
Example 21
Source Project: freeacs   Source File: ParameterParser.java    License: MIT License 5 votes vote down vote up
/**
 * Instantiates a new parameter parser.
 *
 * @param req the req
 * @throws FileUploadException the file upload exception
 */
public ParameterParser(HttpServletRequest req) throws FileUploadException {
  this.req = new AbstractRequest(req);
  isMultipart = ServletFileUpload.isMultipartContent(req);
  // define files anyway so i can use it to return empty enumeration from getFileUploadNames()
  files = new HashMap<>();
  if (isMultipart) {
    // only define params if i need it
    params = new HashMap<>();
    parseUploadParams(req);
  }
}
 
Example 22
Source Project: fess   Source File: FessMultipartRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected ServletFileUpload createServletFileUpload(final HttpServletRequest request) {
    final DiskFileItemFactory fileItemFactory = createDiskFileItemFactory();
    final ServletFileUpload upload = newServletFileUpload(fileItemFactory);
    upload.setHeaderEncoding(request.getCharacterEncoding());
    upload.setSizeMax(getSizeMax());
    return upload;
}
 
Example 23
/**
 * @see MultiPartManager#getPart(cloud.piranha.webapp.api.WebApplication, cloud.piranha.webapp.api.WebApplicationRequest, java.lang.String)
 */
@Override
public Part getPart(WebApplication webApplication,
        WebApplicationRequest request, String name) throws ServletException {

    ApacheMultiPart result = null;
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(FINE, "Getting part: {0} for request: {0}",
                new Object[]{name, request});
    }
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            ServletFileUpload upload = setupFileUpload(webApplication);
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (item.getName().equals(name)) {
                    result = new ApacheMultiPart(item);
                    break;
                }
            }
        } catch (FileUploadException fue) {
            if (LOGGER.isLoggable(WARNING)) {
                LOGGER.log(WARNING, "Error getting part", fue);
            }
        }
    } else {
        throw new ServletException("Not a multipart/form-data request");
    }
    return result;
}
 
Example 24
@PostMapping
protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception {

    String username = securityService.getCurrentUsername(request);

    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }

    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    // Look for file items.
    for (FileItem item : items) {
        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();

            if (StringUtils.isNotBlank(fileName) && data.length > 0) {
                createAvatar(fileName, data, username, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload personal image. No file specified.");
            }
            break;
        }
    }

    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    return new ModelAndView("avatarUploadResult","model",map);
}
 
Example 25
Source Project: rainbow   Source File: UploadHandleServlet.java    License: Apache License 2.0 5 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            if (!ServletFileUpload.isMultipartContent(request))
            {
                return;
            }
            this.fileList = upload.parseRequest(request);
//            System.out.println(fileList.size());
            for (FileItem item : fileList)
            {
                if (item.isFormField())
                {
                    String value = item.getString("UTF-8");
//                  System.out.print(value);
                    names.add(value);
                } else
                {
                    String filename = item.getName();
                    if (filename == null) continue;
                    File newFile = new File(filename);
//            		System.out.println(newFile.getCanonicalPath());
//            		item.write(newFile);
                    this.names.add(newFile.getAbsolutePath().toString());
                    saveFile(item);
                }
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
 
Example 26
Source Project: multiapps-controller   Source File: FilesApiServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private FileItemIterator createFileIterator(HttpServletRequest request) throws IOException, FileUploadException {
    long maxUploadSize = new Configuration().getMaxUploadSize();
    ServletFileUpload upload = getFileUploadServlet();
    upload.setSizeMax(maxUploadSize);
    try {
        return upload.getItemIterator(request);
    } catch (SizeLimitExceededException ex) {
        throw new SLException(MessageFormat.format(Messages.MAX_UPLOAD_SIZE_EXCEEDED, maxUploadSize));
    }
}
 
Example 27
private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) throws Exception {
	SourceBean serviceRequest = requestContext.getServiceRequest();

	// Create a factory for disk-based file items
	FileItemFactory factory = new DiskFileItemFactory();

	// This is done to make upload work in Unix solaris
	// ((DiskFileItemFactory)factory).setSizeThreshold(5242880);

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

	// upload.setFileSizeMax(5242880);
	// upload.setSizeMax(5242880);

	// Parse the request
	List fileItems = upload.parseRequest(request);
	Iterator iter = fileItems.iterator();
	while (iter.hasNext()) {
		FileItem item = (FileItem) iter.next();

		if (item.isFormField()) {
			String name = item.getFieldName();
			String value = item.getString(request.getCharacterEncoding());
			serviceRequest.setAttribute(name, value);
		} else {
			processFileField(item, requestContext);
		}
	}
}
 
Example 28
Source Project: appinventor-extensions   Source File: GalleryServlet.java    License: Apache License 2.0 5 votes vote down vote up
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName)
      throws Exception {
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iterator = upload.getItemIterator(req);
    while (iterator.hasNext()) {
      FileItemStream item = iterator.next();
//      LOG.info(item.getContentType());
      if (item.getFieldName().equals(expectedFieldName)) {
        return item.openStream();
      }
    }
    throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload");
  }
 
Example 29
public void handleFile(HttpServletRequest req) throws FileUploadException {
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    List<FileItem> fileItems = upload.parseRequest(req);

    for (FileItem item : fileItems) {
        System.out.println("Saving " + item.getName() + "...");
    }
}
 
Example 30
Source Project: tutorials   Source File: UploadServlet.java    License: MIT License 5 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (ServletFileUpload.isMultipartContent(request)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            try {
                List<FileItem> formItems = upload.parseRequest(request);

                if (formItems != null && formItems.size() > 0) {
                    for (FileItem item : formItems) {
                        if (!item.isFormField()) {
                            String fileName = new File(item.getName()).getName();
                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);
                            item.write(storeFile);
                            request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
                        }
                    }
                }
            } catch (Exception ex) {
                request.setAttribute("message", "There was an error: " + ex.getMessage());
            }
            getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
        }
    }