当前位置: 首页>>代码示例>>Java>>正文


Java FileItem.getString方法代码示例

本文整理汇总了Java中org.apache.commons.fileupload.FileItem.getString方法的典型用法代码示例。如果您正苦于以下问题:Java FileItem.getString方法的具体用法?Java FileItem.getString怎么用?Java FileItem.getString使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.commons.fileupload.FileItem的用法示例。


在下文中一共展示了FileItem.getString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getMultiParameters

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
 * Retrieve a set of values belonging to a parameter passed to the servlet as part of a multi part
 * content.
 * 
 * @param parameter
 *          The name of the parameter to be retrieved.
 * @param requestFilter
 *          filter used to validate the input against list of allowed inputs
 * @return String array containing the values of the parameter. Empty string if the content is not
 *         multipart.
 */
public String[] getMultiParameters(String parameter, RequestFilter requestFilter) {
  if (!isMultipart || items == null)
    return null;
  Iterator<FileItem> iter = items.iterator();
  Vector<String> result = new Vector<String>();
  while (iter.hasNext()) {
    FileItem item = iter.next();
    if (item.isFormField() && item.getFieldName().equals(parameter)) {
      try {
        String value = item.getString("UTF-8");
        filterRequest(requestFilter, value);
        result.addElement(value);
      } catch (Exception ex) {
      }
    }
  }
  String[] strResult = new String[result.size()];
  result.copyInto(strResult);
  return strResult;
}
 
开发者ID:mauyr,项目名称:openbravo-brazil,代码行数:32,代码来源:VariablesBase.java

示例2: getMultiParameter

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
 * Retrieve a parameter passed to the servlet as part of a multi part content.
 * 
 * @param parameter
 *          the name of the parameter to be retrieved
 * @param requestFilter
 *          filter used to validate the input against list of allowed inputs
 * @return String containing the value of the parameter. Empty string if the content is not
 *         multipart or the parameter is not found.
 */
public String getMultiParameter(String parameter, RequestFilter requestFilter) {
  if (!isMultipart || items == null)
    return "";
  Iterator<FileItem> iter = items.iterator();
  while (iter.hasNext()) {
    FileItem item = iter.next();
    if (item.isFormField() && item.getFieldName().equals(parameter)) {
      try {
        String value = item.getString("UTF-8");
        filterRequest(requestFilter, value);
        return value;
      } catch (Exception ex) {
        ex.printStackTrace();
        return "";
      }
    }
  }
  return "";
}
 
开发者ID:mauyr,项目名称:openbravo-brazil,代码行数:30,代码来源:VariablesBase.java

示例3: processFormField

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
 * Process multipart request item as regular form field. The name and value
 * of each regular form field will be added to the given parameterMap.
 *
 * @param formField    The form field to be processed.
 * @param parameterMap The parameterMap to be used for the HttpServletRequest.
 */
private void processFormField(FileItem formField, Map<String, String[]> parameterMap) {
    String name = formField.getFieldName();
    String value = formField.getString();
    String[] values = parameterMap.get(name);

    if (values == null) {
        // Not in parameter map yet, so add as new value.
        parameterMap.put(name, new String[]{value});
    } else {
        // Multiple field values, so add new value to existing array.
        int length = values.length;
        String[] newValues = new String[length + 1];
        System.arraycopy(values, 0, newValues, 0, length);
        newValues[length] = value;
        parameterMap.put(name, newValues);
    }
}
 
开发者ID:helicalinsight,项目名称:helicalinsight,代码行数:25,代码来源:MultipartFilter.java

示例4: doGet

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
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();
        }
    }
 
开发者ID:dbiir,项目名称:rainbow,代码行数:38,代码来源:UploadHandleServlet.java

示例5: multipartHandler

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@Override
public Map<String, String[]> multipartHandler() throws Exception {
	multipart = new Multipart();
	DiskFileItemFactory disk = new DiskFileItemFactory();
	ServletFileUpload servletFileUpload = new ServletFileUpload(disk);
	List<FileItem> items = servletFileUpload.parseRequest(wrapper.httpRequest());

	Map<String, String[]> params = new HashMap<>();

	for (FileItem fileItem : items) {
		if (fileItem.isFormField()) {
			String fieldName = fileItem.getFieldName();
			String fieldVal = fileItem.getString("UTF-8");
			String[] param = params.get(fieldName);
			
			if (param != null) {
				String[] newArray = new String[param.length + 1];
				System.arraycopy(param, 0, newArray, 0, param.length);
				newArray[param.length] = fieldVal;
				param = newArray;
			} else {
				param = new String[]{fieldVal};
			}
			params.put(fieldName, param);
		} 
		else {
			multipart.addFiles(fileItem);
		}
	}
	return params;
}
 
开发者ID:NymphWeb,项目名称:nymph,代码行数:32,代码来源:ResolverUrlImpl.java

示例6: uploadFiles

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
 * @see http://www.oschina.net/code/snippet_698737_13402
 * @param request
 * @return
 * @throws IOException
 */
public static Map<String, Object> uploadFiles(HttpServlet servlet, HttpServletRequest request) {
    Map<String, Object> map = JwUtils.newHashMap();
    Map<String, String> fileMap = JwUtils.newHashMap();
    map.put("file", fileMap);

    DiskFileItemFactory factory = new DiskFileItemFactory();// 创建工厂
    factory.setSizeThreshold(1024 * 1024 * 30);// 设置最大缓冲区为30M

    // 设置缓冲区目录
    String savePath = servlet.getServletContext().getRealPath("/WEB-INF/temp");
    factory.setRepository(new File(savePath));

    FileUpload upload = new FileUpload(factory);// 获得上传解析器
    upload.setHeaderEncoding("UTF-8");// 解决上传文件名乱码
    
    try {
        String targetFolderPath = servlet.getServletContext().getRealPath("/WEB-INF/" + ConfigUtils.getProperty("web.files.upload.folder"));
        File targetFolder = new File(targetFolderPath);// 目标文件夹
        if(!targetFolder.exists()) {
            targetFolder.mkdir();
        }
        
        List<FileItem> fileItems = upload.parseRequest(new ServletRequestContext(request));// 解析请求体
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {// 判断是普通表单项还是文件上传项
                String name = fileItem.getFieldName();// 表单名
                String value = fileItem.getString("UTF-8");// 表单值
                map.put(name, value);
            } else {// 文件上传项
                String fileName = fileItem.getName();// 获取文件名
                if (StringUtils.isEmpty(fileName))// 判断是否上传了文件
                    continue;

                // 截取文件名
                int index = fileName.lastIndexOf("/");
                if (index > -1) {
                    fileName = fileName.substring(index);
                }

                // 检查文件是否允许上传
                index = fileName.lastIndexOf(".");
                if (index > -1 && index < fileName.length() - 1) {
                    String ext = fileName.substring(index + 1).toLowerCase();
                    if (!ConfigUtils.getString("web.files.upload.extension").contains(";" + ext + ";")) {
                        LOGGER.warn("The file {} is not allowed to upload.", fileName);
                        continue;
                    }
                }

                // 生成唯一文件名,保留原文件名
                String newFileName = UUID.randomUUID().toString();
                
                // 将文件内容写到服务器端
                String targetPath = targetFolderPath + "/" + newFileName;
                File targetFile = new File(targetPath);// 目标文件
                targetFile.createNewFile();
                fileItem.write(targetFile);

                fileItem.delete();// 删除临时文件
                fileMap.put(fileName, newFileName);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}
 
开发者ID:menyouping,项目名称:jw,代码行数:74,代码来源:FileUtils.java

示例7: processFileUpload

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
 * Parse file and save.
 *
 * @param request       request.
 * @param saveDirectory save directory.
 * @throws Exception may be.
 */
private void processFileUpload(HttpRequest request, File saveDirectory) throws Exception {
    FileItemFactory factory = new DiskFileItemFactory(1024 * 1024, saveDirectory);
    HttpFileUpload fileUpload = new HttpFileUpload(factory);

    // Set upload process listener.
    // fileUpload.setProgressListener(new ProgressListener(){...});

    List<FileItem> fileItems = fileUpload.parseRequest(new HttpUploadContext((HttpEntityEnclosingRequest) request));

    for (FileItem fileItem : fileItems) {
        if (!fileItem.isFormField()) { // File param.
            // Attribute.
            // fileItem.getContentType();
            // fileItem.getFieldName();
            // fileItem.getName();
            // fileItem.getSize();
            // fileItem.getString();

            File uploadedFile = new File(saveDirectory, fileItem.getName());
            // 把流写到文件上。
            fileItem.write(uploadedFile);
        } else { // General param.
            String key = fileItem.getName();
            String value = fileItem.getString();
        }
    }
}
 
开发者ID:yanzhenjie,项目名称:AndServer,代码行数:35,代码来源:UploadHandler.java

示例8: initFields

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
  * 处理上传内容
  *
  * @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;
 }
 
开发者ID:ansafari,项目名称:melon,代码行数:67,代码来源:UploadUtils.java

示例9: getParameterMapForMultipart

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
 * File Uploadがある場合のパラメータ解析を行います。
 * @param req HTTPリクエスト。
 * @return パラメータ解析結果。
 * @throws Exception 例外。
 */
private Map<String, Object> getParameterMapForMultipart(final HttpServletRequest req) throws Exception {
	Map<String, Object> map = new HashMap<String, Object>();
	DiskFileItemFactory factory = new DiskFileItemFactory();
	factory.setRepository(new File(tempDir)); //一時的に保存する際のディレクトリ
	ServletFileUpload upload = new ServletFileUpload(factory);
	upload.setHeaderEncoding(encoding);
	@SuppressWarnings("unchecked")
	List<FileItem> list = upload.parseRequest(req);
	for (FileItem item : list) {
		String key = item.getFieldName();
		if (key != null) {
			if (item.isFormField()) {
				String value = item.getString(encoding);
				this.addParamMap(map, key, value);
			} else {
				String filename = item.getName();
				if (StringUtil.isBlank(filename)) {
					map.put(key, null);
				} else {
					map.put(key, item);
				}
			}
		}
	}
	return map;
}
 
开发者ID:takayanagi2087,项目名称:dataforms,代码行数:33,代码来源:DataFormsServlet.java

示例10: parseFileItems

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
	// System.out.println("fileItems:" + fileItems);
	MultipartParsingResult result = super.parseFileItems(fileItems, encoding);

	for (String fieldName : NAMES) {
		if (result.getMultipartFiles().get(fieldName) != null) {
			break;
		}
		FileItem item = this.find(fileItems, fieldName);
		if (item == null) {
			continue;
		}
		String content = item.getString();

		// System.out.println("fieldName:" + fieldName + " content:" + content);
		if (StringUtils.isEmpty(content)) {
			continue;
		}
		if (!content.startsWith("data:image")) {
			continue;
		}
		List<MultipartFile> list = this.toList(result, fieldName, content);
		result.getMultipartFiles().put(fieldName, list);
		// break;
	}
	// CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
	// multipartFiles.add(file.getName(), file);
	return result;
}
 
开发者ID:tanhaichao,项目名称:leopard,代码行数:30,代码来源:LeopardMultipartResolver.java

示例11: performImport

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
private String performImport(List<FileItem> files)  {
    //import certificate
    String status = "";
    InputStream filecontent = null;
    Integer id = null;

    try {
        for (FileItem item : files) {
            if (!item.isFormField()) {
                // Process form file field (input type="file").
                filecontent = item.getInputStream();
            } else {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();

                if (fieldname.equals("id")) {
                    id = Integer.parseInt(fieldvalue);
                }
            }
        }
        if (id != null && filecontent != null) {
            status = importCertificates(id, filecontent);
        }
    } catch (Exception ex) {
        LOGGER.info(ex);
    }

    return "/sharingcenter/security/import.jsp?id=" + id + "&" + status;
}
 
开发者ID:williamgrosset,项目名称:OSCAR-ConCert,代码行数:31,代码来源:SecurityInfrastructureServlet.java

示例12: processTextField

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
private void processTextField(FileItem item, DocFile docFile) {
  String name = item.getFieldName();
  String value = item.getString();    
  if ("rn".equals(name))
    docFile.setRn(Integer.parseInt(value));
  else if ("filename".equals(name))
    docFile.setFilename(value);
  else if ("uploader".equals(name))
    docFile.setUploader(value);
  else if ("contentType".equals(name))
    docFile.setContentType(value);
  
  
}
 
开发者ID:unsftn,项目名称:bisis-v4,代码行数:15,代码来源:FileManagerServlet.java

示例13: doPost

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String fileName = null;
        String filePath = null;
        String path = null;
        InputStream fileContent = null;
        for (FileItem item : items) {
            if (!item.isFormField()) {
                fileContent = item.getInputStream();
                fileName = FilenameUtils.getName(item.getName());
            }else if (item.isFormField() && item.getFieldName() != null
                    && item.getFieldName().equals("filePath")){
                path = item.getString();
            }
        }
        filePath = path + File.separator + fileName;
        OutputStream dest = new FileOutputStream(new
                File(filePath));
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = fileContent.read(bytes)) != -1) {
            dest.write(bytes, 0, read);
        }
        fileContent.close();
        dest.close();

    } catch (FileUploadException e) {
        e.printStackTrace();
        throw new ServletException("Cannot parse multipart request.", e);
    }
    index(request, response);
}
 
开发者ID:fredcampos,项目名称:shellbomb,代码行数:35,代码来源:UploadServlet.java

示例14: createParam

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
 * 创建请求对象
 */
public static Param createParam(HttpServletRequest request) throws IOException {
    List<FormParam> formParamList = new ArrayList<FormParam>();
    List<FileParam> fileParamList = new ArrayList<FileParam>();
    try{
        Map<String, List<FileItem>> fileItemListMap = servletFileUpload.parseParameterMap(request);
        if (CollectionUtil.isNotEmpty(fileItemListMap)) {
            for (Map.Entry<String, List<FileItem>> fileItemListEntry : fileItemListMap.entrySet()) {
                String fieldName = fileItemListEntry.getKey();
                List<FileItem> fileItemList = fileItemListEntry.getValue();
                if (CollectionUtil.isNotEmpty(fileItemList)) {
                    for (FileItem fileItem : fileItemList) {
                        if(fileItem.isFormField()){
                            String fieldValue = fileItem.getString("UTF-8");
                            formParamList.add(new FormParam(fieldName, fieldValue));
                        } else{
                            String fileName = FileUtil.getRealFileName(new String(fileItem.getName().getBytes(), "UTF-8"));
                            if (StringUtil.isNotEmpty(fileName)) {
                                long fileSize = fileItem.getSize();
                                String contentType = fileItem.getContentType();
                                InputStream inputSteam = fileItem.getInputStream();
                                fileParamList.add(new FileParam(fieldName, fileName, fileSize, contentType, inputSteam));
                            }
                        }
                    }
                }
            }
        }
    }catch (FileUploadException e){
        LOGGER.error("create param failure", e);
        throw new RuntimeException(e);
    }
    return new Param(formParamList, fileParamList);
}
 
开发者ID:edagarli,项目名称:Nicole,代码行数:37,代码来源:UploadHelper.java

示例15: processRequest

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
public Object processRequest(HttpServletRequest request) throws Exception {
	HttpServletRequestTwsWrapper twsRequest = request instanceof HttpServletRequestTwsWrapper ? (HttpServletRequestTwsWrapper) request : null;
	File temporaryFile = null;

	try {
		// Check multipart request
		if (ServletFileUpload.isMultipartContent(request)) {
			Engine.logContext.debug("(ServletRequester.initContext) Multipart resquest");

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

			// Set factory constraints
			factory.setSizeThreshold(1000);

			temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp");
			int cptFile = 0;
			temporaryFile.delete();
			temporaryFile.mkdirs();
			factory.setRepository(temporaryFile);
			Engine.logContext.debug("(ServletRequester.initContext) Temporary folder for upload is : " + temporaryFile.getAbsolutePath());

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

			// Set overall request size constraint
			upload.setSizeMax(EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE));
			upload.setFileSizeMax(EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE));

			// Parse the request
			List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));

			for (FileItem fileItem : items) {
				String parameterName = fileItem.getFieldName();
				String parameterValue;
				if (fileItem.isFormField()) {
					parameterValue = fileItem.getString();
					Engine.logContext.trace("(ServletRequester.initContext) Value for field '" + parameterName + "' : " + parameterValue);
				} else {
					String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1");
					if (name.length() > 0) {
						File wDir = new File(temporaryFile, "" + (++cptFile));
						wDir.mkdirs();
						File wFile = new File(wDir, name);
						fileItem.write(wFile);
						fileItem.delete();
						parameterValue = wFile.getAbsolutePath();
						Engine.logContext.debug("(ServletRequester.initContext) Temporary uploaded file for field '" + parameterName + "' : " + parameterValue);
					} else {
						Engine.logContext.debug("(ServletRequester.initContext) No temporary uploaded file for field '" + parameterName + "', empty name");
						parameterValue = "";
					}
				}

				if (twsRequest != null) {
					twsRequest.addParameter(parameterName, parameterValue);
				}
			}
		}
		
		Requester requester = getRequester();
		request.setAttribute("convertigo.requester", requester);

		Object result = requester.processRequest(request);

		processRequestEnd(request, requester);
		
		return result;
	} finally {
		if (temporaryFile != null) {
			try {
				Engine.logEngine.debug("(GenericServlet) Removing the temporary file : " + temporaryFile.getAbsolutePath());
				FileUtils.deleteDirectory(temporaryFile);
			} catch (IOException e) { }
		}
	}
}
 
开发者ID:convertigo,项目名称:convertigo-engine,代码行数:78,代码来源:GenericServlet.java


注:本文中的org.apache.commons.fileupload.FileItem.getString方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。