Java Code Examples for org.apache.commons.fileupload.FileItem#getFieldName()

The following examples show how to use org.apache.commons.fileupload.FileItem#getFieldName() . 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
Source File: ParseUploadUtil.java    From S-mall-servlet with GNU General Public License v3.0 6 votes vote down vote up
/**
 *
 * @param request Servlet请求
 * @param params 一个预备的键值表储存非文件流的参数Map
 * @return 上传的文件流
 */
public static InputStream parseUpload(HttpServletRequest request, Map<String,String> params){
    InputStream is = null;
    try{
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        factory.setSizeThreshold(10*1024*1024);
        List<FileItem> items= upload.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                is = item.getInputStream();
            } else {
                String paramName = item.getFieldName();
                String paramValue = item.getString();
                paramValue = new String(paramValue.getBytes("ISO-8859-1"), "UTF-8");
                params.put(paramName, paramValue);
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return is;
}
 
Example 2
Source File: AdapterPortlet.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private void handleMultipartForm(ActionRequest 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
	PortletFileUpload upload = new PortletFileUpload(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 3
Source File: AdapterHTTP.java    From Knowage-Server with 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 4
Source File: AdapterPortlet.java    From Knowage-Server with 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(ActionRequest 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
	PortletFileUpload upload = new PortletFileUpload(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 5
Source File: UploadDatasetFileResource.java    From Knowage-Server with 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 6
Source File: AdapterHTTP.java    From Knowage-Server with 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 7
Source File: PackageServletHandler.java    From urule with 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 8
Source File: PoseidonServlet.java    From Poseidon with 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 9
Source File: ParsingFormData.java    From Mars-Java with MIT License 5 votes vote down vote up
/**
 * 解析
 * @param exchange 请求对象
 * @param marsParams 参数
 * @param files 文件
 * @param contentType 内容类型
 * @return 参数和文件
 */
public static Map<String,Object> parsing(HttpExchange exchange, Map<String, List<String>> marsParams, Map<String, MarsFileUpLoad> files, String contentType) throws Exception {
    Map<String,Object> result = new HashMap<>();

    List<FileItem> fileItemList = getFileItem(exchange,contentType);

    for(FileItem item : fileItemList){
        if(item.isFormField()){
            String name = item.getFieldName();
            String value = item.getString(MarsConstant.ENCODING);
            List<String> params = marsParams.get(name);
            if(params == null){
                params = new ArrayList<>();
            }
            params.add(value);
            marsParams.put(name,params);
        } else {
            MarsFileUpLoad marsFileUpLoad = new MarsFileUpLoad();
            marsFileUpLoad.setName(item.getFieldName());
            marsFileUpLoad.setInputStream(item.getInputStream());
            marsFileUpLoad.setFileName(item.getName());
            files.put(marsFileUpLoad.getName(),marsFileUpLoad);
        }
    }

    result.put(PARAMS_KEY,marsParams);
    result.put(FILES_KEY,files);
    return result;
}
 
Example 10
Source File: JobUploadService.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private String[] processUploadedFile(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor) throws ZipException, IOException, SpagoBIEngineException {
	String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();
    
    if(fieldName.equalsIgnoreCase("deploymentDescriptor")) return null;
    
    RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();
    File jobsDir = new File(runtimeRepository.getRootDir(), jobDeploymentDescriptor.getLanguage().toLowerCase());
	File projectDir = new File(jobsDir, jobDeploymentDescriptor.getProject());
	File tmpDir = new File(projectDir, "tmp");
	if(!tmpDir.exists()) tmpDir.mkdirs();	   
     File uploadedFile = new File(tmpDir, fileName);
    
    try {
		item.write(uploadedFile);
	} catch (Exception e) {
		e.printStackTrace();
	}	
	
	String[] dirNames = ZipUtils.getDirectoryNameByLevel(new ZipFile(uploadedFile), 2);
	List dirNameList = new ArrayList();
	for(int i = 0; i < dirNames.length; i++) {
		if(!dirNames[i].equalsIgnoreCase("lib")) dirNameList.add(dirNames[i]);
	}
	String[] jobNames = (String[])dirNameList.toArray(new String[0]);
	
    runtimeRepository.deployJob(jobDeploymentDescriptor, new ZipFile(uploadedFile));
    uploadedFile.delete();	
    tmpDir.delete();
    
    return jobNames;
}
 
Example 11
Source File: FessMultipartRequestHandler.java    From fess with Apache License 2.0 5 votes vote down vote up
protected void addTextParameter(final HttpServletRequest request, final FileItem item) {
    final String name = item.getFieldName();
    final String encoding = request.getCharacterEncoding();
    String value = null;
    boolean haveValue = false;
    if (encoding != null) {
        try {
            value = item.getString(encoding);
            haveValue = true;
        } catch (final Exception e) {}
    }
    if (!haveValue) {
        try {
            value = item.getString("ISO-8859-1");
        } catch (final java.io.UnsupportedEncodingException uee) {
            value = item.getString();
        }
        haveValue = true;
    }
    if (request instanceof MultipartRequestWrapper) {
        final MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request;
        wrapper.setParameter(name, value);
    }
    final String[] oldArray = elementsText.get(name);
    final String[] newArray;
    if (oldArray != null) {
        newArray = new String[oldArray.length + 1];
        System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
        newArray[oldArray.length] = value;
    } else {
        newArray = new String[] { value };
    }
    elementsText.put(name, newArray);
    elementsAll.put(name, newArray);
}
 
Example 12
Source File: UploadServlet.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	// �ж��ϴ����Ƿ�����ļ�
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if (isMultipart) {
		// ��ȡ·��
		String realpath = request.getSession().getServletContext()
				.getRealPath("/files");
		System.out.println(realpath);

		File dir = new File(realpath);
		if (!dir.exists())
			dir.mkdirs();
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		try {
			// ����������� ��ʵ���� form����ÿ��input�ڵ�
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// ����DZ� ����ÿ���� ��ӡ������̨
					String name1 = item.getFieldName();// �õ��������������
					String value = item.getString("UTF-8");// �õ�����ֵ
					System.out.println(name1 + "=" + value);
				} else {
					// ���ļ�д����ǰservlet����Ӧ��·��
					item.write(new File(dir, System.currentTimeMillis()
							+ item.getName().substring(
									item.getName().lastIndexOf("."))));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 13
Source File: podHomeBean.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
	 * Creates a BufferedInputStream to get ready to upload file selected. Used
	 * by Add Podcast and Revise Podcast pages.
	 * 
	 * @param event
	 *            ValueChangeEvent object generated by selecting a file to
	 *            upload.
	 *            
	 * @throws AbortProcessingException
	 * 			Internal processing error attempting to set up BufferedInputStream
	 */
	public void processFileUpload(ValueChangeEvent event)
			throws AbortProcessingException {
		UIComponent component = event.getComponent();

		Object newValue = event.getNewValue();
		Object oldValue = event.getOldValue();
		PhaseId phaseId = event.getPhaseId();
		Object source = event.getSource();
//		log.info("processFileUpload() event: " + event
//				+ " component: " + component + " newValue: " + newValue
//				+ " oldValue: " + oldValue + " phaseId: " + phaseId
//				+ " source: " + source);

		if (newValue instanceof String)
			return;
		if (newValue == null)
			return;

		FileItem item = (FileItem) event.getNewValue();
		String fieldName = item.getFieldName();
		filename = FilenameUtils.getName(item.getName());
		fileSize = item.getSize();
		fileContentType = item.getContentType();
//		log.info("processFileUpload(): item: " + item
//				+ " fieldname: " + fieldName + " filename: " + filename
//				+ " length: " + fileSize);

		// Read the file as a stream (may be more memory-efficient)
		try {
			fileAsStream = new BufferedInputStream(item.getInputStream());
			
		} 
		catch (IOException e) {
			log.warn("IOException while attempting to set BufferedInputStream to upload "
							+ filename + " from site " + podcastService.getSiteId() + ". "
									 + e.getMessage(), e);
			setErrorMessage(INTERNAL_ERROR_ALERT);

		}

	}
 
Example 14
Source File: SshService.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_HTML)
@GenerateLink(rel = Constants.LINK_REL_CREATE_PAIR)
public Response createPair(Iterator<FileItem> formData)
    throws BadRequestException, ServerException, ConflictException {
  String service = null;
  String name = null;
  String privateKey = null;
  String publicKey = null;

  while (formData.hasNext()) {
    FileItem item = formData.next();
    String fieldName = item.getFieldName();
    switch (fieldName) {
      case "service":
        service = item.getString();
        break;
      case "name":
        name = item.getString();
        break;
      case "privateKey":
        privateKey = item.getString();
        break;
      case "publicKey":
        publicKey = item.getString();
        break;
      default:
        // do nothing
    }
  }

  requiredNotNull(service, "Service name required");
  requiredNotNull(name, "Name required");
  if (privateKey == null && publicKey == null) {
    throw new BadRequestException("Key content was not provided.");
  }

  sshManager.createPair(
      new SshPairImpl(getCurrentUserId(), service, name, publicKey, privateKey));

  // We should send 200 response code and body with empty line
  // through specific of html form that doesn't invoke complete submit handler
  return Response.ok("", MediaType.TEXT_HTML).build();
}
 
Example 15
Source File: UploadUtils.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * 处理上传内容
 * 
 * @param request
 * @param maxSize
 * @return
 */
@SuppressWarnings("unchecked")
private Map<String, Object> initFields(HttpServletRequest request) {

	// 存储表单字段和非表单字段
	Map<String, Object> map = new HashMap<String, Object>();

	// 第一步:判断request
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	// 第二步:解析request
	if (isMultipart) {
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 阀值,超过这个值才会写到临时目录,否则在内存中
		factory.setSizeThreshold(1024 * 1024 * 10);
		factory.setRepository(new File(tempPath));

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

		upload.setHeaderEncoding("UTF-8");

		// 最大上传限制
		upload.setSizeMax(maxSize);

		/* FileItem */
		List<FileItem> items = null;
		// Parse the request
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 第3步:处理uploaded items
		if (items != null && items.size() > 0) {
			Iterator<FileItem> iter = items.iterator();
			// 文件域对象
			List<FileItem> list = new ArrayList<FileItem>();
			// 表单字段
			Map<String, String> fields = new HashMap<String, String>();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				// 处理所有表单元素和文件域表单元素
				if (item.isFormField()) { // 表单元素
					String name = item.getFieldName();
					String value = item.getString();
					fields.put(name, value);
				} else { // 文件域表单元素
					list.add(item);
				}
			}
			map.put(FORM_FIELDS, fields);
			map.put(FILE_FIELDS, list);
		}
	}
	return map;
}
 
Example 16
Source File: UploadVideoController.java    From TinyMooc with Apache License 2.0 4 votes vote down vote up
@RequestMapping("uploadAll.htm")
public ModelAndView uploadAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
    User user = (User) request.getSession().getAttribute("user");

    String courseIntro = null, lessonNum = null, courseTitle = null, message = null, courseId = null;
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory disk = new DiskFileItemFactory();
        disk.setSizeThreshold(20 * 1024);
        disk.setRepository(disk.getRepository());
        ServletFileUpload up = new ServletFileUpload(disk);
        int maxsize = 1000 * 1024 * 1024;
        List list = up.parseRequest(request);
        Iterator i = list.iterator();
        String resourceUrl = "";
        String postfix = "";
        while (i.hasNext()) {
            FileItem fm = (FileItem) i.next();
            if (!fm.isFormField()) {

                String filePath = fm.getName();
                String fileName = "";
                int startIndex = filePath.lastIndexOf("\\");
                if (startIndex != -1) {
                    fileName = filePath.substring(startIndex + 1);
                } else {
                    fileName = filePath;
                }
                resourceUrl = fileName;

                if (fm.getSize() > maxsize) {
                    message = "文件太大,不超过1000M";
                    break;
                }
                String filepath = "D:\\GitHub\\TinyMooc\\src\\main\\webapp\\resource\\video";
                postfix = resourceUrl.substring(resourceUrl.lastIndexOf(".") + 1, resourceUrl.length());
                File uploadPath = new File(filepath);
                File saveFile = new File(uploadPath, fileName);
                fm.write(saveFile);
                message = "文件上传成功!";
            } else {
                String formName = fm.getFieldName();
                String con = fm.getString("utf-8");
                if (formName.equals("courseIntro")) {
                    courseIntro = con;
                } else if (formName.equals("lessonNum")) {
                    lessonNum = con;
                } else if (formName.equals("courseTitle")) {
                    courseTitle = con;
                } else if (formName.equals("courseId")) {
                    courseId = con;
                }
            }
        }
        Course course = new Course();
        course.setCourseId(UUIDGenerator.randomUUID());
        course.setApplyDate(new Date());
        course.setCourse(uploadService.findById(Course.class, courseId));
        course.setCourseIntro(courseIntro);
        course.setCourseState("申请中");
        course.setCourseTitle(courseTitle);
        course.setLessonNum(Integer.parseInt(lessonNum));
        course.setScanNum(0);
        uploadService.save(course);

        UserCourse uC = new UserCourse();
        uC.setCourse(course);
        uC.setUserCourseId(UUIDGenerator.randomUUID());
        uC.setUserPosition("创建者");
        uC.setUser(user);
        uploadService.save(uC);

        Resource resource = new Resource();
        resource.setResourceId(UUIDGenerator.randomUUID());
        resource.setResourceObject(course.getCourseId());
        resource.setType("video");
        uploadService.save(resource);

        Video video = new Video();

        video.setResourceId(resource.getResourceId());
        video.setResource(resource);
        video.setVideoUrl(resourceUrl);

        uploadService.save(video);
        return new ModelAndView("redirect:courseDetailPage.htm?courseId=" + courseId);

    }
    return new ModelAndView("redirect:courseDetailPage.htm?courseId=" + courseId);
}
 
Example 17
Source File: FileUploadUtils.java    From TinyMooc with Apache License 2.0 4 votes vote down vote up
public static final HashMap UploadFile(HttpServletRequest request, HttpServletResponse response, String filepaths) throws Exception {
    HashMap params = new HashMap();
    String pathType = "images";
    if (!(filepaths.equals("")))
        pathType = filepaths;
    String readPath = "";
    String contextPath = "";
    if ((readPath == null) || (readPath.equals("")))
        readPath = request.getSession().getServletContext().getRealPath("");

    if ((contextPath == null) || (contextPath.equals("")))
        contextPath = request.getContextPath();

    String savePhotoPath = mkdirFile(readPath, pathType, true);
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory dff = new DiskFileItemFactory();
        dff.setSizeThreshold(1024000);
        ServletFileUpload sfu = new ServletFileUpload(dff);
        List fileItems = sfu.parseRequest(request);
        sfu.setFileSizeMax(5000000L);
        sfu.setSizeMax(10000000L);
        sfu.setHeaderEncoding("UTF-8");
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = new String(item.getString().getBytes(
                        "ISO8859-1"), "utf-8");
                params.put(name, value);
            } else if ((item.getSize() > 0L) &&
                    (item.getName() != null)) {
                File fullFile = new File(item.getName());
                File fileOnServer = new File(savePhotoPath,
                        fullFile.getName());
                item.write(fileOnServer);
                String fileName2 = fileOnServer.getName();
                String fileType = fileName2.substring(fileName2
                        .lastIndexOf("."));
                String filepath = savePhotoPath + "/" +
                        new Date().getTime() + fileType;
                File newFile = new File(filepath);
                fileOnServer.renameTo(newFile);
                String returnString = filepath.substring(readPath
                        .length());
                params.put(item.getFieldName(), request.getRequestURL().toString().replace(request.getRequestURI(), "") + contextPath +
                        returnString);
            }
        }
    }

    return params;
}
 
Example 18
Source File: UploadUtils.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
/**
	 * 处理上传内容
	 * 
	 * @param request
	 * @param maxSize
	 * @return
	 */
//	@SuppressWarnings("unchecked")
	private Map<String, Object> initFields(HttpServletRequest request) {

		// 存储表单字段和非表单字段
		Map<String, Object> map = new HashMap<String, Object>();

		// 第一步:判断request
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		// 第二步:解析request
		if (isMultipart) {
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// 阀值,超过这个值才会写到临时目录,否则在内存中
			factory.setSizeThreshold(1024 * 1024 * 10);
			factory.setRepository(new File(tempPath));

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

			upload.setHeaderEncoding("UTF-8");

			// 最大上传限制
			upload.setSizeMax(maxSize);

			/* FileItem */
			List<FileItem> items = null;
			// Parse the request
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// 第3步:处理uploaded items
			if (items != null && items.size() > 0) {
				Iterator<FileItem> iter = items.iterator();
				// 文件域对象
				List<FileItem> list = new ArrayList<FileItem>();
				// 表单字段
				Map<String, String> fields = new HashMap<String, String>();
				while (iter.hasNext()) {
					FileItem item = iter.next();
					// 处理所有表单元素和文件域表单元素
					if (item.isFormField()) { // 表单元素
						String name = item.getFieldName();
						String value = item.getString();
						fields.put(name, value);
					} else { // 文件域表单元素
						list.add(item);
					}
				}
				map.put(FORM_FIELDS, fields);
				map.put(FILE_FIELDS, list);
			}
		}
		return map;
	}
 
Example 19
Source File: UploadUtils.java    From jeewx with Apache License 2.0 4 votes vote down vote up
/**
 * 处理上传内容
 * 
 * @param request
 * @param maxSize
 * @return
 */
@SuppressWarnings("unchecked")
private Map<String, Object> initFields(HttpServletRequest request) {

	// 存储表单字段和非表单字段
	Map<String, Object> map = new HashMap<String, Object>();

	// 第一步:判断request
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	// 第二步:解析request
	if (isMultipart) {
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 阀值,超过这个值才会写到临时目录,否则在内存中
		factory.setSizeThreshold(1024 * 1024 * 10);
		factory.setRepository(new File(tempPath));

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

		upload.setHeaderEncoding("UTF-8");

		// 最大上传限制
		upload.setSizeMax(maxSize);

		/* FileItem */
		List<FileItem> items = null;
		// Parse the request
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 第3步:处理uploaded items
		if (items != null && items.size() > 0) {
			Iterator<FileItem> iter = items.iterator();
			// 文件域对象
			List<FileItem> list = new ArrayList<FileItem>();
			// 表单字段
			Map<String, String> fields = new HashMap<String, String>();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				// 处理所有表单元素和文件域表单元素
				if (item.isFormField()) { // 表单元素
					String name = item.getFieldName();
					String value = item.getString();
					fields.put(name, value);
				} else { // 文件域表单元素
					list.add(item);
				}
			}
			map.put(FORM_FIELDS, fields);
			map.put(FILE_FIELDS, list);
		}
	}
	return map;
}
 
Example 20
Source File: UploadHelper.java    From smart-framework with Apache License 2.0 4 votes vote down vote up
/**
 * 创建 multipart 请求参数列表
 */
public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception {
    // 定义参数列表
    List<Object> paramList = new ArrayList<Object>();
    // 创建两个对象,分别对应 普通字段 与 文件字段
    Map<String, Object> fieldMap = new HashMap<String, Object>();
    List<Multipart> multipartList = new ArrayList<Multipart>();
    // 获取并遍历表单项
    List<FileItem> fileItemList;
    try {
        fileItemList = fileUpload.parseRequest(request);
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // 异常转换(抛出自定义异常)
        throw new UploadException(e);
    }
    for (FileItem fileItem : fileItemList) {
        // 分两种情况处理表单项
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            // 处理普通字段
            String fieldValue = fileItem.getString(FrameworkConstant.UTF_8);
            fieldMap.put(fieldName, fieldValue);
        } else {
            // 处理文件字段
            String fileName = FileUtil.getRealFileName(fileItem.getName());
            if (StringUtil.isNotEmpty(fileName)) {
                long fileSize = fileItem.getSize();
                String contentType = fileItem.getContentType();
                InputStream inputSteam = fileItem.getInputStream();
                // 创建 Multipart 对象,并将其添加到 multipartList 中
                Multipart multipart = new Multipart(fieldName, fileName, fileSize, contentType, inputSteam);
                multipartList.add(multipart);
            }
        }
    }
    // 初始化参数列表
    paramList.add(new Params(fieldMap));
    paramList.add(new Multiparts(multipartList));
    // 返回参数列表
    return paramList;
}