當前位置: 首頁>>代碼示例>>Java>>正文


Java FileItem.delete方法代碼示例

本文整理匯總了Java中org.apache.commons.fileupload.FileItem.delete方法的典型用法代碼示例。如果您正苦於以下問題:Java FileItem.delete方法的具體用法?Java FileItem.delete怎麽用?Java FileItem.delete使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.commons.fileupload.FileItem的用法示例。


在下文中一共展示了FileItem.delete方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: processNormalFormField

import org.apache.commons.fileupload.FileItem; //導入方法依賴的package包/類
protected void processNormalFormField(FileItem item, String charset) throws UnsupportedEncodingException {
    LOG.debug("Item is a normal form field");

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

    // note: see http://jira.opensymphony.com/browse/WW-633
    // basically, in some cases the charset may be null, so
    // we're just going to try to "other" method (no idea if this
    // will work)
    if (charset != null) {
        values.add(item.getString(charset));
    } else {
        values.add(item.getString());
    }
    params.put(item.getFieldName(), values);
    item.delete();
}
 
開發者ID:txazo,項目名稱:struts2,代碼行數:23,代碼來源:JakartaMultiPartRequest.java

示例2: cleanUp

import org.apache.commons.fileupload.FileItem; //導入方法依賴的package包/類
public void cleanUp() {
    Set<String> names = files.keySet();
    for (String name : names) {
        List<FileItem> items = files.get(name);
        for (FileItem item : items) {
            if (LOG.isDebugEnabled()) {
                String msg = LocalizedTextUtil.findText(this.getClass(), "struts.messages.removing.file",
                        Locale.ENGLISH, "no.message.found", new Object[]{name, item});
                LOG.debug(msg);
            }
            if (!item.isInMemory()) {
                item.delete();
            }
        }
    }
}
 
開發者ID:txazo,項目名稱:struts2,代碼行數:17,代碼來源:JakartaMultiPartRequest.java

示例3: processFileField

import org.apache.commons.fileupload.FileItem; //導入方法依賴的package包/類
/**
 * Process multipart request item as file field. The name and FileItem
 * object of each file field will be added as attribute of the given
 * HttpServletRequest. If a FileUploadException has occurred when the file
 * size has exceeded the maximum file size, then the FileUploadException
 * will be added as attribute value instead of the FileItem object.
 *
 * @param fileField The file field to be processed.
 * @param request   The involved HttpServletRequest.
 */
private void processFileField(FileItem fileField, HttpServletRequest request) {
    if (fileField.getName().length() <= 0) {
        // No file uploaded.
        request.setAttribute(fileField.getFieldName(), null);
    } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
        // File size exceeds maximum file size.
        request.setAttribute(fileField.getFieldName(), new FileUploadException("File size " +
                "exceeds maximum file size of " + maxFileSize + " bytes."));
        // Immediately delete temporary file to free up memory and/or disk
        // space.
        fileField.delete();
    } else {
        // File uploaded with good size.
        request.setAttribute(fileField.getFieldName(), fileField);
    }
}
 
開發者ID:helicalinsight,項目名稱:helicalinsight,代碼行數:27,代碼來源:MultipartFilter.java

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

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

示例6: getFileParameterValue

import org.apache.commons.fileupload.FileItem; //導入方法依賴的package包/類
/**
 * Responsible for constructing a FileBean object for the named file parameter. If there is no
 * file parameter with the specified name this method should return null.
 *
 * @param name the name of the file parameter
 * @return a FileBean object wrapping the uploaded file
 */
public FileBean getFileParameterValue(String name) {
    final FileItem item = this.files.get(name);
    if (item == null
            || ((item.getName() == null || item.getName().length() == 0) && item.getSize() == 0)) {
        return null;
    }
    else {
        // Attempt to ensure the file name is just the basename with no path included
        String filename = item.getName();
        int index;
        if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find())
            index = filename.lastIndexOf('\\');
        else
            index = filename.lastIndexOf('/');
        if (index >= 0 && index + 1 < filename.length() - 1)
            filename = filename.substring(index + 1);

        // Use an anonymous inner subclass of FileBean that overrides all the
        // methods that rely on having a File present, to use the FileItem
        // created by commons upload instead.
        return new FileBean(null, item.getContentType(), filename, this.charset) {
            @Override public long getSize() { return item.getSize(); }

            @Override public InputStream getInputStream() throws IOException {
                return item.getInputStream();
            }

            @Override public void save(File toFile) throws IOException {
                try {
                    item.write(toFile);
                    delete();
                }
                catch (Exception e) {
                    if (e instanceof IOException) throw (IOException) e;
                    else {
                        IOException ioe = new IOException("Problem saving uploaded file.");
                        ioe.initCause(e);
                        throw ioe;
                    }
                }
            }

            @Override
            public void delete() throws IOException { item.delete(); }
        };
    }
}
 
開發者ID:nkasvosve,項目名稱:beyondj,代碼行數:55,代碼來源:CommonsMultipartWrapper.java


注:本文中的org.apache.commons.fileupload.FileItem.delete方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。