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.
Example 1
Project: Poseidon   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 2
Project: BigDataPlatform   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 3
Project: rebuild   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 4
Project: piranha   File: ApacheMultiPartManager.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @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 5
Project: openrasp-testcases   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 6
Project: openrasp-testcases   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 7
Project: urule   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 8
Project: urule   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 9
Project: mumu   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 10
Project: Knowage-Server   File: UploadDatasetFileResource.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 11
Project: rice   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 12
Project: Knowage-Server   File: AdapterHTTP.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 13
Project: Knowage-Server   File: AdapterHTTP.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 14
Project: rdf4j   File: WorkbenchRequest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 15
Project: airsonic-advanced   File: AvatarUploadController.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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 16
Project: spring-analysis-note   File: CommonsMultipartResolverTests.java    License: MIT License 5 votes vote down vote up
@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 17
Project: ttt   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 18
Project: smart-framework   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 19
Project: java-technology-stack   File: CommonsMultipartResolverTests.java    License: MIT License 5 votes vote down vote up
@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 20
Project: freeacs   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 21
Project: fess   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 22
Project: piranha   File: ApacheMultiPartManager.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @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 23
Project: airsonic   File: AvatarUploadController.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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 24
Project: rainbow   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 25
Project: multiapps-controller   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 26
Project: Knowage-Server   File: AdapterHTTP.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 27
Project: appinventor-extensions   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 28
Project: Android_Code_Arbiter   File: FileUploadCommon.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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 29
Project: tutorials   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);
        }
    }
 
Example 30
Project: jeecg   File: Uploader.java    License: Apache License 2.0 5 votes vote down vote up
private void parseParams() {

		DiskFileItemFactory dff = new DiskFileItemFactory();
		try {
			ServletFileUpload sfu = new ServletFileUpload(dff);
			sfu.setSizeMax(this.maxSize);
			sfu.setHeaderEncoding(Uploader.ENCODEING);

			FileItemIterator fii = sfu.getItemIterator(this.request);

			while (fii.hasNext()) {
				FileItemStream item = fii.next();
				// 普通参数存储
				if (item.isFormField()) {

					this.params.put(item.getFieldName(),
							this.getParameterValue(item.openStream()));

				} else {

					// 只保留一个
					if (this.inputStream == null) {
						this.inputStream = item.openStream();
						this.originalName = item.getName();
						return;
					}

				}

			}

		} catch (Exception e) {
			this.state = this.errorInfo.get("UNKNOWN");
		}

	}
 
Example 31
Project: rdf4j   File: WorkbenchRequest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 32
Project: carbon-identity-framework   File: SecurityUIUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static List parseRequest(ServletRequestContext requestContext)
        throws FileUploadException {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    return upload.parseRequest(requestContext);
}
 
Example 33
Project: spring4-understanding   File: CommonsMultipartResolverTests.java    License: Apache License 2.0 5 votes vote down vote up
@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<FileItem>();
			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 34
Project: spring4-understanding   File: AbstractJettyServerTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	assertTrue(ServletFileUpload.isMultipartContent(req));
	FileItemFactory factory = new DiskFileItemFactory();
	ServletFileUpload upload = new ServletFileUpload(factory);
	try {
		List<FileItem> items = upload.parseRequest(req);
		assertEquals(4, items.size());
		FileItem item = items.get(0);
		assertTrue(item.isFormField());
		assertEquals("name 1", item.getFieldName());
		assertEquals("value 1", item.getString());

		item = items.get(1);
		assertTrue(item.isFormField());
		assertEquals("name 2", item.getFieldName());
		assertEquals("value 2+1", item.getString());

		item = items.get(2);
		assertTrue(item.isFormField());
		assertEquals("name 2", item.getFieldName());
		assertEquals("value 2+2", item.getString());

		item = items.get(3);
		assertFalse(item.isFormField());
		assertEquals("logo", item.getFieldName());
		assertEquals("logo.jpg", item.getName());
		assertEquals("image/jpeg", item.getContentType());
	}
	catch (FileUploadException ex) {
		throw new ServletException(ex);
	}

}
 
Example 35
Project: aws-serverless-java-container   File: AwsHttpServletRequest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings({"FILE_UPLOAD_FILENAME", "WEAK_FILENAMEUTILS"})
protected Map<String, Part> getMultipartFormParametersMap() {
    if (multipartFormParameters != null) {
        return multipartFormParameters;
    }
    if (!ServletFileUpload.isMultipartContent(this)) { // isMultipartContent also checks the content type
        multipartFormParameters = new HashMap<>();
        return multipartFormParameters;
    }
    Timer.start("SERVLET_REQUEST_GET_MULTIPART_PARAMS");
    multipartFormParameters = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

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

    try {
        List<FileItem> items = upload.parseRequest(this);
        for (FileItem item : items) {
            String fileName = FilenameUtils.getName(item.getName());
            AwsProxyRequestPart newPart = new AwsProxyRequestPart(item.get());
            newPart.setName(item.getFieldName());
            newPart.setSubmittedFileName(fileName);
            newPart.setContentType(item.getContentType());
            newPart.setSize(item.getSize());
            item.getHeaders().getHeaderNames().forEachRemaining(h -> {
                newPart.addHeader(h, item.getHeaders().getHeader(h));
            });

            multipartFormParameters.put(item.getFieldName(), newPart);
        }
    } catch (FileUploadException e) {
        Timer.stop("SERVLET_REQUEST_GET_MULTIPART_PARAMS");
        log.error("Could not read multipart upload file", e);
    }
    Timer.stop("SERVLET_REQUEST_GET_MULTIPART_PARAMS");
    return multipartFormParameters;
}
 
Example 36
Project: subsonic   File: ImportPlaylistController.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();

    try {
        if (ServletFileUpload.isMultipartContent(request)) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (Object o : items) {
                FileItem item = (FileItem) o;

                if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) {
                    if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) {
                        throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB.");
                    }
                    String playlistName = FilenameUtils.getBaseName(item.getName());
                    String fileName = FilenameUtils.getName(item.getName());
                    String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName()));
                    String username = securityService.getCurrentUsername(request);
                    Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, format, item.getInputStream(), null);
                    map.put("playlist", playlist);
                }
            }
        }
    } catch (Exception e) {
        map.put("error", e.getMessage());
    }

    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}
 
Example 37
Project: nexus-public   File: HttpPartIteratorAdapter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Iterator<PartPayload> iterator() {
  try {
    final FileItemIterator itemIterator = new ServletFileUpload().getItemIterator(httpRequest);
    return new PayloadIterator(itemIterator);
  }
  catch (FileUploadException | IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 38
Project: ymate-platform-v2   File: FileUploadHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param processer 文件上传处理器
 * @return 处理表单提交,使用提供的文件上传处理器处理文件流
 * @throws FileUploadException 文件上传时可能产生的异常
 * @throws IOException         文件读写可能产生的异常
 */
public UploadFormWrapper processUpload(IUploadFileItemProcesser processer) throws FileUploadException, IOException {
    boolean _isMultipart = ServletFileUpload.isMultipartContent(__request);
    if (_isMultipart) {
        if (null != processer) {
            return __doUploadFileAsStream(processer);
        } else {
            return UploadFileAsDiskBased();
        }
    }
    return new UploadFormWrapper();
}
 
Example 39
Project: openprodoc   File: AddDocAdv.java    License: GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean AddDoc(HttpServletRequest Req) throws PDException, FileUploadException, IOException
{
String FileName=null;
InputStream FileData=null;
HashMap ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }
String Acept=(String) ListFields.get("BOk");
if (Acept==null || Acept.length()==0)
    return(false);
DriverGeneric PDSession=SParent.getSessOPD(Req);
String DType=(String) ListFields.get(PDDocs.fDOCTYPE);
PDDocs Doc;
if (DType==null)
    Doc = new PDDocs(PDSession);
else
    Doc = new PDDocs(PDSession, DType);
Record Rec=Doc.getRecSum();
Rec.initList();
Attribute Attr=Rec.nextAttr();
while (Attr!=null)
    {
    if (!List.contains(Attr.getName()))
        {
        String Val=(String) ListFields.get(Attr.getName());
        if (Attr.getType()==Attribute.tBOOLEAN)
            {
            if(Val == null)
                Attr.setValue(false);
            else
                Attr.setValue(true);
            }
        else if(Val != null)
            {
            SParent.FillAttr(Req, Attr, Val, false);
            }
        }
    Attr=Rec.nextAttr();
    }
Doc.assignValues(Rec);
Doc.setParentId(getActFolderId(Req));
String RefFile=(String) ListFields.get(PDDocs.fNAME+"_");
if (RefFile!=null && RefFile.length()!=0)
    {
    Doc.setFile(RefFile);
    }
else
    {
    Doc.setName(FileName);
    PDMimeType mt=new PDMimeType(PDSession);
    Doc.setMimeType(mt.SolveName(FileName));
    Doc.setStream(FileData);
    }
Doc.insert();
return(true);
}
 
Example 40
Project: incubator-retired-wave   File: AttachmentServlet.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
    IOException {
  // Process only multipart requests.
  if (ServletFileUpload.isMultipartContent(request)) {
    // 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.
    try {
      @SuppressWarnings("unchecked")
      List<FileItem> items = upload.parseRequest(request);
      AttachmentId id = null;
      String waveRefStr = null;
      FileItem fileItem = null;
      for (FileItem item : items) {
        // Process only file upload - discard other form item types.
        if (item.isFormField()) {
          if (item.getFieldName().equals("attachmentId")) {
            id = AttachmentId.deserialise(item.getString());
          }
          if (item.getFieldName().equals("waveRef")) {
            waveRefStr = item.getString();
          }
        } else {
          fileItem = item;
        }
      }

      if (id == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No attachment Id in the request.");
        return;
      }
      if (waveRefStr == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No wave reference in request.");
        return;
      }

      WaveletName waveletName = AttachmentUtil.waveRef2WaveletName(waveRefStr);
      ParticipantId user = sessionManager.getLoggedInUser(request.getSession(false));
      boolean isAuthorized = waveletProvider.checkAccessPermission(waveletName, user);
      if (!isAuthorized) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
      }

      // Get only the file name not whole path.
      if (fileItem != null && fileItem.getName()  != null) {
        String fileName = FilenameUtils.getName(fileItem.getName());
        service.storeAttachment(id, fileItem.getInputStream(), waveletName, fileName, user);
        response.setStatus(HttpServletResponse.SC_CREATED);
        String msg =
            String.format("The file with name: %s and id: %s was created successfully.",
                fileName, id);
        LOG.fine(msg);
        response.getWriter().print("OK");
        response.flushBuffer();
      }
    } catch (Exception e) {
      LOG.severe("Upload error", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
          "An error occurred while upload the file : " + e.getMessage());
    }
  } else {
    LOG.severe("Request contents type is not supported by the servlet.");
    response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
        "Request contents type is not supported by the servlet.");
  }
}