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


Java FileItem.getName方法代码示例

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


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

示例1: processUploadedFile

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
 * 解析上传域
 *
 * @param item 文件对象
 * @return {@link FileFormResult}
 * @throws IOException IO异常
 */
private FileFormResult processUploadedFile(FileItem item) throws IOException {
    String name = item.getName();
    String fileSuffix = FilenameUtils.getExtension(name);
    if (CollectionUtils.isNotEmpty(allowedSuffixList) && !allowedSuffixList.contains(fileSuffix)) {
        throw new NotAllowedUploadException(String.format("上传文件格式不正确,fileName=%s,allowedSuffixList=%s",
                name, allowedSuffixList));
    }
    FileFormResult file = new FileFormResult();
    file.setFieldName(item.getFieldName());
    file.setFileName(name);
    file.setContentType(item.getContentType());
    file.setSizeInBytes(item.getSize());

    //如果未设置上传路径,直接保存到项目根目录
    if (Strings.isNullOrEmpty(baseDir)) {
        baseDir = request.getRealPath("/");
    }
    File relativePath = new File(SEPARATOR + DateFormatUtils.format(new Date(), "yyyyMMdd") + file.getFileName());
    FileCopyUtils.copy(item.getInputStream(), new FileOutputStream(relativePath));
    file.setSaveRelativePath(relativePath.getAbsolutePath());
    return file;
}
 
开发者ID:glameyzhou,项目名称:scaffold,代码行数:30,代码来源:Uploader.java

示例2: processFileField

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
protected void processFileField(FileItem item) {
    LOG.debug("Item is a file upload");

    // Skip file uploads that don't have a file name - meaning that no file was selected.
    if (item.getName() == null || item.getName().trim().length() < 1) {
        LOG.debug("No file has been uploaded for the field: {}", item.getFieldName());
        return;
    }

    List<FileItem> values;
    if (files.get(item.getFieldName()) != null) {
        values = files.get(item.getFieldName());
    } else {
        values = new ArrayList<>();
    }

    values.add(item);
    files.put(item.getFieldName(), values);
}
 
开发者ID:txazo,项目名称:struts2,代码行数:20,代码来源:JakartaMultiPartRequest.java

示例3: FileData

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
FileData(FileItem item)
{
	this.fileName = item.getName();
	this.type = item.getContentType();
	this.data = item.get();
	
	if(fileName != null)
	{
		int i = fileName.lastIndexOf("/");
		if(i>0)
		{
			fileName = fileName.substring(i+1);
		}
		else
		{
			i = fileName.lastIndexOf("\\");
			if(i>0)
    		{
    			fileName = fileName.substring(i+1);
    		}
		}
	}
	
	this.item = item;
}
 
开发者ID:fancimage,项目名称:tern,代码行数:26,代码来源:FileData.java

示例4: executePost

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
public void executePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String path = getPath(request);
	String thePath = fileBasePath+"uploads/"; //TODO calculate the directory path for this file
	/////////////////////////////
	//TODO: thePath will be dependent on a verb retrieved from request
	/////////////////////////////
	String verb = getVerb(path);
	String userId = "";
	if (verb.equals("uUpload") ||
		verb.equals("muUpload")) {
		System.out.println("UserUpload "+thePath);
		//user upload
		userId = getUserId(path);
		String tempPath = thePath+userId;
		File dir = new File(tempPath);
		if (!dir.exists()) {
			boolean foo = dir.mkdir();
			System.out.println("MADEDIR "+foo);
		}
		thePath = dir.getAbsolutePath();
	}
	try {
		System.out.println("UPLOADING TO "+verb+" | "+userId+" | "+thePath);
		File repository = new File(thePath);
    	String uploadPath = repository.getAbsolutePath()+"/";
    	DiskFileItemFactory dfiFactory = dfiFactory = new DiskFileItemFactory();
    	dfiFactory.setRepository(repository);
		ServletFileUpload servletFileUpload = new ServletFileUpload(dfiFactory);
		System.out.println("PARSING");
		List<FileItem> items = servletFileUpload.parseRequest(request);
		System.out.println("FILEUPLOADING "+path+
				" | "+items.size());
		Iterator<FileItem> iter = items.iterator();
   		while (iter.hasNext()) {
   		    FileItem item = iter.next();
	    	String fileName = item.getName();

   		    if (item.isFormField()) {
   		        //TODO processFormField(item);
   		    } else {
   		        //TODOprocessUploadedFile(item);
   		    	File f = new File(uploadPath+fileName);
   		    	item.write(f);
   		    }
   		    //TODO would be nice to have a socket and show progress
   		} 		} catch (Exception e) {
		environment.logError(e.getMessage(), e);
		e.printStackTrace();
	}
	if (verb.equals("uUpload"))
		response.sendRedirect("/gui");
	else
		sendHTML("ok", response);
}
 
开发者ID:topicquests,项目名称:backside-servlet-ks,代码行数:55,代码来源:UploadHelper.java

示例5: handleRequestInternal

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@RequestMapping(method = RequestMethod.POST)
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<?> items = upload.parseRequest(request);

    // Look for file items.
    for (Object o : items) {
        FileItem item = (FileItem) o;

        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);
}
 
开发者ID:airsonic,项目名称:airsonic,代码行数:38,代码来源:AvatarUploadController.java

示例6: 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

示例7: doUpload

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@Override
protected void doUpload(HttpServletRequest request, Document document, FileItem item) throws Exception {		
	File fullFile = new File(item.getName());
	String certifNameExtension=fullFile.getName().replaceFirst(".*\\.", ".");
	if(CertificateManager.isCertificateExtension(certifNameExtension)){
		File savedFile = new File(getRepository(), fullFile.getName());
		item.write(savedFile);			
		ServiceUtils.addMessage(document, document.getDocumentElement(), "The certificate \""+fullFile.getName()+"\" has been successfully uploaded", "message", false);
	}
	else{
		ServiceUtils.addMessage(document, document.getDocumentElement(), "The extension \""+certifNameExtension+"\" isn't valid", "error", false);
	}
}
 
开发者ID:convertigo,项目名称:convertigo-engine,代码行数:14,代码来源:Install.java

示例8: execute

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@Override
public FileUploadRpcResponse execute(FileUploadRpcRequest request, SessionContext helper) {
	if (request.isReset()) {
		helper.setAttribute(UploadServlet.SESSION_LAST_FILE, null);
		return new FileUploadRpcResponse();
	} else {
		FileItem file = (FileItem)helper.getAttribute(UploadServlet.SESSION_LAST_FILE);
		return (file == null ? new FileUploadRpcResponse() : new FileUploadRpcResponse(file.getName()));
	}
}
 
开发者ID:Jenner4S,项目名称:unitimes,代码行数:11,代码来源:FileUploadBackend.java

示例9: receiveFile

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@SuppressWarnings({ "unchecked" })
	private void receiveFile(HttpServletRequest request, OnFileReceiveListener listener) throws Exception{
		
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 临时文件夹路径
		String repositoryPath = ConfigManager.getManager().FILE_TEMP_PATH;
		// 设定临时文件夹为repositoryPath
		File fileTempFolder = new File(repositoryPath);
		if(!fileTempFolder.exists())fileTempFolder.mkdirs();
		factory.setRepository(fileTempFolder);

		// 设定上传文件的阈值,如果上传文件大于1M,就可能在repository
		// 所代 表的文件夹中产生临时文件,否则直接在内存中进行处理
		factory.setSizeThreshold(1024 * 1024);

		// 创建一个ServletFileUpload对象
		ServletFileUpload uploader = new ServletFileUpload(factory);

			// 调用uploader中的parseRequest方法,可以获得请求中的相关内容,
			// 即一个FileItem类型的ArrayList。FileItem是在
			// org.apache.commons.fileupload中定义的,它可以代表一个文件,
			// 也可以代表一个普通的form field
			ArrayList<FileItem> list = (ArrayList<FileItem>) uploader.parseRequest(request);
			for (FileItem fileItem : list){
				if (!fileItem.isFormField()){ // 如果是文件
					String fileName = fileItem.getName() + UUID.randomUUID();
					// 将其中包含的内容写到指定目录下名为fileName的文件中
					File file = new File(ConfigManager.getManager().FILE_SAVE_PATH + File.separator + fileName);
					file.createNewFile();
//					System.out.println(file.getPath());
					fileItem.write(file);
					
					listener.onFinished(MD5.getMD5CodeByFile(file),fileName,file.length());
					break;//一次请求只接受一个文件
				}
			}
	}
 
开发者ID:landriesnidis,项目名称:PCloud_Server_v3,代码行数:39,代码来源:UploadAction.java

示例10: HttpUploadReader

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
HttpUploadReader(FileItem item) throws IOException {
    this.item = item;
    fieldName = item.getFieldName();
    fileName = item.getName();
    contentType = item.getContentType();
    size = item.getSize();
    inputStream = item.getInputStream();
}
 
开发者ID:heisedebaise,项目名称:tephra,代码行数:9,代码来源:HttpUploadReader.java

示例11: 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

示例12: 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

示例13: getFile

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
private InputStream getFile(VariablesSecureApp vars) throws IOException {
  FileItem fi = vars.getMultiFile("inpFile");
  if (fi == null)
    throw new IOException("Invalid filename");
  filename = fi.getName();
  InputStream in = fi.getInputStream();
  if (in == null)
    throw new IOException("Corrupted file");
  return in;
}
 
开发者ID:mauyr,项目名称:openbravo-brazil,代码行数:11,代码来源:FIN_BankStatementImport.java

示例14: handleRequestInternal

import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) 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<?> items = upload.parseRequest(request);

    // Look for file items.
    for (Object o : items) {
        FileItem item = (FileItem) o;

        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));
    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}
 
开发者ID:sindremehus,项目名称:subsonic,代码行数:40,代码来源:AvatarUploadController.java

示例15: 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


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