`

commons-fileupload的优化实用类

阅读更多

commons-fileupload这东西上传和保存文件很方便,但读取里面的field的值的时候就很麻烦,总是循环一遍并比较名字才能取到值,极其不便,于是不得不做了个实用类,进行封装,用起来好多了,并且可以直接保存文件,我觉得还是挺方便的,共享一下吧。

 

原先取域的值的时候,代码类似如下:

for (FileItem item : items) {
				if (item.isFormField()) {
					fieldName = item.getFieldName();
					if (fieldName.equals("email")) {
						email= item.getString("UTF-8").trim();
					} else if (fieldName.equals("username")) {
						username = item.getString("UTF-8").trim();
					} 

 

    有一两个field问题不大,但如果有几十个呢,上百个呢?代码就很冗长和乏味了。

 

    用了我写的UploadForm,取值就跟读取普通表单的field一样容易,如:

String email = uploadForm.getStringField("email");

   

    完整代码如下,重要的地方写了注释:

    

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.*;
import com.liferay.portal.util.PortalUtil;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;

import javax.portlet.PortletRequest;
import javax.servlet.http.HttpServletRequest;

import java.io.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

public class UploadForm {
    private static Log log = LogFactoryUtil.getLog(UploadForm.class);
    private HttpServletRequest request;
    private HashMap<String, Object> fields = new HashMap<String, Object>();
    private List<FileItem> oriFileItems = new ArrayList<FileItem>();


    public UploadForm(HttpServletRequest request) {
        this.request = request;
        init();
    }

    public UploadForm(PortletRequest request) {
        this(PortalUtil.getHttpServletRequest(request));
    }

    private void init() {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload uploader = new ServletFileUpload(factory);
        try {
            List<FileItem> items = uploader.parseRequest(request);
            for (FileItem item : items) {
                oriFileItems.add(item);
                String fieldName = item.getFieldName();
                log.debug("field name: " + fieldName);
                if (item.isFormField()) {
                    String fieldValue = null;
                    try {
                        fieldValue = item.getString("utf-8");
                    } catch (UnsupportedEncodingException e) {
                        log.error(e);
                    }

                    if (fields.get(fieldName) != null) {
                        Object value = fields.get(fieldName);
                        if (value instanceof List) {
                            ((List) value).add(item.getString());
                        } else {
                            fields.put(fieldName, ListUtil.fromArray(new String[]{String.valueOf(value), fieldValue}));
                        }
                    } else {
                        try {
                            fields.put(fieldName, item.getString("utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            log.error(e);
                        }
                    }
                } else { //it's a file
                    if (fields.get(fieldName) != null) {
                        Object value = fields.get(fieldName);
                        if (value instanceof List) {
                            ((List) value).add(item.getString());
                        } else {
                            fields.put(fieldName, ListUtil.fromArray(new Object[]{value, item}));
                        }
                    } else {//first time checked
                        fields.put(fieldName, item);
                    }

                }
            }
        } catch (FileUploadException e) {
            log.error(e);
        }
    }

    /**
     * get the values of form fields
     *
     * @param fieldName
     * @return return "" if nothing is input for non-checkbox or non-radiobutton,
     *          return null if nothing is selected for checkbox or radiobutton
     */
    public String getStringField(String fieldName) {
        return MapUtil.getString(fields, fieldName);
    }

    public long getLongField(String fieldName) {
        if (StringUtils.isNotEmpty(getStringField(fieldName))) {
            return Long.parseLong(getStringField(fieldName));
        } else {
            return -1;
        }
    }

    public int getIntField(String fieldName) {
        if (StringUtils.isNotEmpty(getStringField(fieldName))) {
            return Integer.parseInt(getStringField(fieldName));
        } else {
            return -1;
        }
    }

    public float getFloatField(String fieldName) {
        if (StringUtils.isNotEmpty(getStringField(fieldName))) {
            return Float.parseFloat(getStringField(fieldName));
        } else {
            return -1;
        }
    }

    public double getDoubleField(String fieldName) {
        if (StringUtils.isNotEmpty(getStringField(fieldName))) {
            return Double.parseDouble(getStringField(fieldName));
        } else {
            return -1;
        }
    }

    /**
     * 取多值field的值,如checkbox
     * @param fieldName
     * @return
     */
    public String[] getStringFields(String fieldName) {
        if (!fields.containsKey(fieldName)) {
            return new String[0];
        }

        Object value = fields.get(fieldName);
        if (value instanceof List) {
            List<String> listValue = (List) value;
            return listValue.toArray(new String[0]);
        } else {
            return new String[]{String.valueOf(fields.get(fieldName))};
        }
    }

    /**
     * 取多值字段的原始FileItem
     * @param fieldName
     * @return
     */
    public FileItem[] getFileItemFields(String fieldName){
        if (!fields.containsKey(fieldName)){
            return new FileItem[]{};
        }

        if (fields.get(fieldName) instanceof List){
            List<FileItem> listField = (List)fields.get(fieldName);
            return listField.toArray(new FileItem[0]);
        }else{
            return new FileItem[]{((FileItem) fields.get(fieldName))};
        }
    }

    public Object getField(String fieldName) {
        return fields.get(fieldName);
    }

    /**
     * 保存文件
     *
     * @param fieldName 表单项的名字
     * @param saveName  保存文件名,含扩展名,不含文件夹部分
     * @param folder    保存的文件夹
     * @return
     */
    public FileWrapper saveFile(String fieldName, String saveName, String folder) {
        if (fields.get(fieldName) instanceof List){
            throw new IllegalArgumentException("Duplicated file selector['"+fieldName+"'] found! Ensure only one exists");
        }

        FileItem fileItem = (FileItem) fields.get(fieldName);
        if (!FileUtil.exists(folder)) {
            FileUtil.mkdirs(folder);
        }

        String fullPath = folder.replaceAll("\\\\", "/") + "/" + saveName;
        if (FileUtil.exists(fullPath)) {
            return null;
        } else {
            try {
                File file = new File(fullPath);
                fileItem.write(file);
                FileWrapper rspFile = new FileWrapper(file);
                rspFile.setOldName(fileItem.getName());
                return rspFile;
            } catch (Exception e) {
                log.error(e);
                return null;
            }
        }
    }

    /**
     * 用原先的文件名保存文件
     *
     * @param fieldName
     * @param folder
     * @return
     */
    public FileWrapper saveFile(String fieldName, String folder) {
        FileItem fileItem = (FileItem) fields.get(fieldName);
        return saveFile(fieldName, fileItem.getName(), folder);
    }

    /**
     * 用UUID作为文件名保存文件
     *
     * @param fieldName
     * @param folder
     * @return
     */
    public FileWrapper saveFileWithUUID(String fieldName, String folder) {
        FileItem fileItem = (FileItem) fields.get(fieldName);
        String oriFileName = fileItem.getName();
        String fileName = oriFileName.contains(".") ? UUID.randomUUID().toString() + "." + FileUtil.getExtension(oriFileName)
                : UUID.randomUUID().toString();
        return saveFile(fieldName, fileName, folder);
    }

    public FileWrapper saveFileItem(FileItem fileItem, String saveName, String folder) {
        if (StringUtils.isEmpty(fileItem.getName())){
            return null;
        }

        if (!FileUtil.exists(folder)) {
            FileUtil.mkdirs(folder);
        }

        String fullPath = folder.replaceAll("\\\\", "/") + "/" + saveName;
        if (FileUtil.exists(fullPath)) {
            return null;
        } else {
            try {
                File file = new File(fullPath);
                fileItem.write(file);
                FileWrapper rspFile = new FileWrapper(file);
                rspFile.setOldName(fileItem.getName());
                return rspFile;
            } catch (Exception e) {
                log.error(e);
                return null;
            }
        }

    }

    public FileWrapper saveFileWithUUID(FileItem fileItem, String folder) {
        String oriFileName = fileItem.getName();
        if (StringUtils.isEmpty(oriFileName)){
        	return null;
        }
        
        String fileName = oriFileName.contains(".") ? UUID.randomUUID().toString() + "." + FileUtil.getExtension(oriFileName)
                : UUID.randomUUID().toString();
        return saveFileItem(fileItem,fileName,folder);
    }

    public List<FileWrapper> saveFilesWithUUID(List<FileItem> fileItemList, String folder) {
        List<FileWrapper> files=new ArrayList<FileWrapper>();
        for (FileItem fileItem : fileItemList) {
            files.add(saveFileWithUUID(fileItem, folder));
        }

        return files;
    }

    public List<FileWrapper> saveFilesWithUUID(String fieldName, String folder) {
        FileItem[] fileItems=getFileItemFields(fieldName);
        List<FileWrapper> files=new ArrayList<FileWrapper>();

        for (FileItem fileItem : fileItems) {
            files.add(saveFileWithUUID(fileItem, folder));
        }

        return files;
    }

    /**
     * 按名称关键字搜索字段并返回FileItem数组,对于有些field,名字前缀一样,但可能加个不同的序号
     * 适合于动态添加的表单域
     * @param fieldNameKeyword
     * @return
     */
    public FileItem[] getFileItemArrByKeyword(String fieldNameKeyword){
        List<FileItem> fileItemList=new ArrayList<FileItem>();
        for (FileItem fileItem : oriFileItems) {
            if (fileItem.getFieldName().toLowerCase().contains(fieldNameKeyword.toLowerCase())){
                fileItemList.add(fileItem);
            }
        }

        return getFileItemListByKeyword(fieldNameKeyword).toArray(new FileItem[0]);
    }
    
    public List<FileItem> getFileItemListByKeyword(String fieldNameKeyword){
    	return getFileItemListByKeyword(fieldNameKeyword,true);
    }

    public List<FileItem> getFileItemListByKeyword(String fieldNameKeyword, boolean isFile){
        List<FileItem> fileItemList=new ArrayList<FileItem>();
        for (FileItem fileItem : oriFileItems) {
            if (fileItem.getFieldName().toLowerCase().contains(fieldNameKeyword.toLowerCase())){
                if (isFile){
                    if (!fileItem.isFormField() && fileItem.getSize()>0){
                        fileItemList.add(fileItem);
                    }
                }else{
                    fileItemList.add(fileItem);
                }
            }
        }

        return fileItemList;
    }
    

    public String[] getStringArrByKeyword(String fieldNameKeyword){
        return getStringListByKeyword(fieldNameKeyword).toArray(new String[0]);
    }
    
    public List<String> getStringListByKeyword(String fieldNameKeyword){
    	 List<String> strItemList=new ArrayList<String>();
         for (FileItem fileItem : oriFileItems) {
             if (fileItem.getFieldName().toLowerCase().contains(fieldNameKeyword.toLowerCase())){
                 try {
                     strItemList.add(fileItem.getString("UTF-8"));
                 } catch (UnsupportedEncodingException e) {
                     log.error(e);
                 }
             }
         }
         
         return strItemList;
    }
    

    public long getFileByteSize(String fieldName) {
        FileItem fileItem = (FileItem) fields.get(fieldName);
        return fileItem.getSize();
    }

    /**
     * 取得文件大小,单位KB
     * @param fieldName
     * @return
     */
    public float getFileKBSize(String fieldName) {
        return getFileByteSize(fieldName) / 1024.0f;
    }

    public double getFileMBSize(String fieldName) {
        return getFileByteSize(fieldName) / 1024.0 / 1024;
    }

    public boolean exist(String fieldName) {
        return fields.containsKey(fieldName);
    }

}

 

    用到的文件包装器,可以返回上传文件的原始名字,url编码后的名字等等,便于下载用到:

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.FileUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * 文件的实用类,含有一些实用的方法
 */
public class FileWrapper {
    private static Log log = LogFactoryUtil.getLog(FileWrapper.class);
    private File file;
    private String oldName;

    public FileWrapper(File file) {
        this.file = file;
    }

    public String getFileName(){
        return file.getName();
    }

    /**
     * 获得文件被保存的路径,不含文件名
     * @return
     */
    public String getFolderPath(){
        return FileUtil.getPath(file.getAbsolutePath());
    }

    /**
     * 将文件名转码成url中用的编码
     * @return
     */
    public String getUrlEncodingName(){
        try {
            return java.net.URLEncoder.encode(oldName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error(e);
            return "";
        }
    }

    /**
     * 获得文件原始名
     * @return
     */
    public String getOldName() {
        return oldName;
    }

    public void setOldName(String oldName) {
        if (oldName.contains("\\") || oldName.contains("/")){
            oldName = oldName.replaceAll("\\\\","/");
            oldName = oldName.substring(oldName.lastIndexOf("/"));
            this.oldName = oldName;
        }else{
            this.oldName = oldName;
        }
    }

    public String getExtName(){
        return FileUtil.getExtension(file.getAbsolutePath());
    }
    
    public String getFullPath(){
    	return file.getAbsolutePath();
    }
}

 

    调用示例:

 UploadForm uploadForm=new UploadForm(request);
 
  String zip_code = uploadForm.getStringField("zip_code");
    List<String> provinces = uploadForm.getStringListByKeyword("province");//省份字段是在页面动态添加的
    List<FileWrapper> certFileList = uploadForm.saveFilesWithUUID(uploadForm.getFileItemListByKeyword("certFile"), "d:/upload");//上传文件的保存

 

    通过这种封装,以后使用commons-fileupload就不再是一件头疼的事了。不过,代码中用到了一少部分liferay的一些实用类,可以根据需要很容易地自己写或其它开源类库替换

分享到:
评论

相关推荐

    commons-fileupload-1.3.3.jar和commons-io-2.6.jar

    在Java开发中,上传文件是一项常见的任务,而`commons-fileupload-1.3.3.jar`和`commons-io-2.6.jar`是Apache Commons项目中的两个重要库,专门用于处理HTTP请求中的文件上传功能。这两个库为开发者提供了便捷、高效...

    commons-fileupload-1.3.3.jar commons-io-2.5.jar

    Apache Commons IO则是Apache Commons项目中的另一个关键组件,它提供了大量与I/O(输入/输出)相关的实用工具类。`commons-io-2.5.jar` 包含了各种I/O操作的通用功能,如文件读写、流操作、文件比较、文件过滤等。...

    commons-fileupload-1.3.jar和commons-io-1.2.jar.zip

    - 输入/输出流:提供各种实用的流处理类,如`TeeInputStream`用于将输入流复制到多个目的地,`FilterInputStream`用于添加过滤器。 - 文件比较:`FileUtils.contentEquals`方法可以比较两个文件的内容是否相同。 ...

    commons-fileupload-1.3.3&commons-fileupload-1.3.3架包和代码.rar

    描述中提及的"commons-io-2.2"是Apache Commons IO库的2.2版本,这是一个非常实用的Java I/O工具集,包含了大量与输入/输出相关的实用类,如文件操作、流操作、转换和比较等,它是FileUpload库的一个依赖,提供了...

    commons-fileupload.rar;包括commons-fileupload-1.3.1-bin和commons-io-2.4

    7. **与其他库的集成**:`commons-fileupload`通常与`commons-io`一起使用,后者提供了许多实用的I/O操作函数,例如文件复制、删除、读写等。 8. **版本更新**:`1.3.1`相对于早期版本可能包含了一些性能优化、bug...

    commons-fileupload-1.2.1.jar与commons-io-1.3.2.jar

    在处理文件上传时,`commons-fileupload`可能会依赖`commons-io`来完成一些底层的文件操作,比如读写文件、复制文件、检查文件是否存在等。`1.3.2`同样表示这个库的一个特定版本,它可能包含了更多的功能和改进。 ...

    commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar

    在进行Web文件上传时,开发者通常会先将`commons-fileupload`和`commons-io`这两个库添加到项目的类路径中。然后,使用FileUpload的`DiskFileItemFactory`创建一个工厂实例,配置内存和磁盘的处理策略。接着,通过`...

    commons-fileupload-1.2.2.jar和commons-io.jar

    这两个库是Apache Commons项目的一部分,Apache Commons是Java社区的一个子项目,旨在为开发人员提供高质量的实用工具类。 `commons-fileupload` 库主要专注于处理HTTP协议中的文件上传请求。在Web应用中,特别是...

    commons-fileupload组件和commons-io组件

    Apache Commons项目提供了两个非常实用的组件,即Commons-Fileupload和Commons-IO,来帮助开发者处理这一任务。这两个组件是Java Web开发中的重要工具,特别是对于初学者来说,它们简化了文件上传的复杂过程。 **...

    commons-fileupload-1.3.1.jar

    Apache Commons是Apache软件基金会的一个项目集合,它提供了许多实用工具类和组件,用于解决Java编程中的常见问题。"commons"标签表明这个库是Apache Commons项目的一部分,旨在提供通用的、可重用的Java组件。 在...

    commons-fileupload-1.3.3-bin

    Apache Commons IO是另一个实用库,提供了一系列与I/O相关的工具类,包括文件操作、流处理、读写字符和字节等。在处理文件上传时, Commons IO库常常作为辅助库,帮助处理文件的读写和复制等任务。 总的来说,...

    commons-fileupload-1.3.2jar包和commons-io-2.5jar包.zip

    接下来,Apache Commons IO是一个通用的I/O工具库,提供了大量实用类和方法,用于处理文件、流、字符集转换、读写操作等。例如,你可以使用这个库来创建、复制、移动或删除文件,读取和写入文件内容,以及进行各种...

    commons-fileupload-1.3.2.jar和commons-io-2.5.jar

    Apache Commons IO库,"commons-io-2.5.jar",则是对Java标准IO类库的扩展,提供了大量的实用工具类,用于文件和流的操作。在文件上传过程中,Commons IO库可以用于读取、写入、复制、比较和操作文件。例如,当...

    commons-fileupload-1.2.1.jar和commons-io-1.4.jar

    1. 将`commons-fileupload-1.2.1.jar`和`commons-io-1.4.jar`添加到项目的类路径(classpath)中。 2. 创建一个Servlet来处理文件上传请求,使用`FileItemFactory`创建一个工厂实例,然后使用`ServletFileUpload`...

    commons-fileupload-1.2.2.jar和commons-io-2.4.jar包

    在处理文件上传和下载的过程中,IO库提供了许多实用工具类和方法,如文件的创建、删除、复制、重命名,以及读写文件内容等。在与FileUpload库配合使用时,IO库可以方便地进行文件的读写和临时存储,确保文件上传过程...

    commons-io-1.4.jar和commons-fileupload-1.3.1.jar

    此外,FileUpload库还提供了处理上传文件大小限制、内存溢出预防等实用功能。 这两个库通常一起使用,以实现完整的文件上传功能。例如,当用户在Web表单中选择一个或多个文件并提交后,服务器端的Servlet会接收到一...

    commons-fileupload-1.2.jar和commons-io-1.3.2.jar

    `commons-fileupload-1.2.jar`是该库的一个特定版本,它包含了处理文件上传的核心类和方法,例如`DiskFileItemFactory`用于配置临时存储文件的方式,以及`ServletFileUpload`用于解析HTTP请求中的文件数据。...

    commons-fileupload-1.0上传组件使用实例.

    在Web开发中,特别是在Java Web应用中,`commons-fileupload`是一个非常实用的工具。 #### 二、安装与配置 为了使用`commons-fileupload`,首先需要将其添加到项目的依赖库中。如果是Maven项目,可以在`pom.xml`...

    struts2上传文件需要的jar包 commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar

    `commons-io-1.3.2.jar`则是Apache Commons IO库的版本1.3.2,它提供了各种IO操作的实用工具类,如文件读写、复制、移动、重命名等。在处理文件上传时,`commons-io`库中的`FileUtils`类可以帮助我们方便地进行文件...

Global site tag (gtag.js) - Google Analytics