当前位置: 首页>>代码示例>>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;未经允许,请勿转载。