當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。