ajaxFileUpload文件上传后台通用代码



import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.log4j.Logger;

//import sun.util.logging.resources.logging;


/**
 * 通用文件上传
 *
 * @author Wang
 * @date 2013-07-20
 */
public class Upload{

    /**
     * 上传后,将InputStream保存到封装的map中
     */
    public static int FILESTREAM=1;
    /**
     * 上传后,将文件转化为二进制保存
     */
    public static int FILEBYTES=2;
    /**
     *
     */
    public static int FILE=3;


    private String fileName = "";

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    private static String filePath ="";
    private static long maxUploadSize = 1024*512*1024;
    private static String headerEncoding ="UTF-8";
    Logger log = Logger.getLogger(getClass());

    /**
     * 默认上传最大上限
     * 保存类型为FILESTREAM
     * @param request
     * @return
     */
    public Map upload(HttpServletRequest request){
        return upload(request,maxUploadSize,FILESTREAM);
    }

    /**
     *判断filePhth路径中是否存在该文件夹,不存在则创建该文件夹
     *创建成功则返回True
     * @param filePhth
     * @return
     **/
    public boolean createFile(String filePhth){
        File dirFile;
        boolean bFile = false;
        try{
            dirFile = new File(filePhth);
            bFile = dirFile.exists();
            if(bFile != true){
                bFile = dirFile.mkdir();
            }
        }catch(Exception e)
        {
        }
        return bFile;
    }

    static{
        Properties r = PropertiesHelper.loadProperty("/upload.properties");
        if(!r.isEmpty()){
            try{
                filePath = r.getProperty("filePath");

            }catch(Exception e){
                Logger.getLogger(Upload.class).error("无法读filePath参数",e);
            }
            try{
                headerEncoding = r.getProperty("headerEncoding");

            }catch(Exception e){
                Logger.getLogger(Upload.class).error("无法读headerEncoding参数",e);
            }
            try{
                maxUploadSize = Long.parseLong(String.valueOf(r.get("maxUploadSize")));
            }catch(Exception e){
                Logger.getLogger(Upload.class).error("无法读maxUploadSize参数",e);
            }}else{
            Logger.getLogger(Upload.class).error("无法读取 upload.properties");
        }
    }




    /**
     * @param request
     * @param size 上传文件大小上限
     * @param type 保存类型 1、保存InputStream,2保存bytes
     * @return
     */
    public Map upload(HttpServletRequest request,long size,int type){

        Map map = new HashMap();
        DiskFileUpload fileUpload = new DiskFileUpload();
        fileUpload.setSizeMax(size==0?maxUploadSize:size);//最大上传大小
        fileUpload.setHeaderEncoding("UTF-8");
        fileUpload.setSizeThreshold(4096);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        FileItem fileItem=null;
        String oldFileName = "";
        try {
            List itemList = fileUpload.parseRequest(request);
            for(Iterator iterator = itemList.iterator();iterator.hasNext();){
                fileItem = (FileItem)iterator.next();
                System.out.println("--------maps----------"+fileItem.isFormField());
                if(fileItem.isFormField()){
                    map.put(fileItem.getFieldName(), fileItem.getString());
                }else{
                    if(type==FILESTREAM){
                        map.put(fileItem.getFieldName(), fileItem.getInputStream());
                    }else if(type==FILEBYTES){
                        InputStream in = fileItem.getInputStream();
                        byte[] b = new byte[in.available()];
                        in.read(b);
                        map.put(fileItem.getFieldName(), b);
                    }else{
                        String strPhthString = filePath+File.separator+ File.separator;
                        oldFileName = fileItem.getName();
                        map.put("FILE_NAME", oldFileName.substring(oldFileName.lastIndexOf(File.separator)+1, oldFileName.length()));
                        map.put("FILE_SIZE", new Long(fileItem.getSize()));
                        fileName = fileName + oldFileName.substring(oldFileName.lastIndexOf("."), oldFileName.length());//存储文件名;

                        map.put(fileItem.getFieldName(), fileName);//该参数为生成的文件夹和文件名连在一起
                        createFile(strPhthString);
                        map.put("FILE_PATH", fileName);

                        fileItem.write(new File(strPhthString + fileName));
                    }
                }
            }
            log.error("upload:"+map);
            return map;
        }catch(SizeLimitExceededException e){
            map.clear();
            map.put("error","file to large. The max size is"+fileUpload.getSizeMax());
        } catch (FileUploadException e) {
            map.clear();
            map.put("error",e.getMessage());
        } catch (IOException e) {
            map.clear();
            map.put("error",e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            map.put("error",e.getMessage());
        }
        return map;
    }



    /**
     * @param request
     * @param size 上传文件大小上限
     * @param type 保存类型 1、保存InputStream,2保存bytes
     * @return
     */
    public Map upload2(HttpServletRequest request,long size,int type){
        Map map = new HashMap();
        DiskFileUpload fileUpload = new DiskFileUpload();
        fileUpload.setSizeMax(size);//最大上传大小
        FileItem fileItem=null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String oldFileName = "";
        try {
            List itemList = fileUpload.parseRequest(request);
            String strPhthString = request.getRealPath("/")+"/upimage/" + sdf.format(new Date());
            for(Iterator iterator = itemList.iterator();iterator.hasNext();){
                fileItem = (FileItem)iterator.next();
                if(fileItem.isFormField()){
                    map.put(fileItem.getFieldName(), fileItem.getString());
                }else{
                    if(type==FILESTREAM){
                        map.put(fileItem.getFieldName(), fileItem.getInputStream());
                    }else if(type==FILEBYTES){
                        InputStream in = fileItem.getInputStream();
                        byte[] b = new byte[in.available()];
                        in.read(b);
                        map.put(fileItem.getFieldName(), b);
                    }else{
                        oldFileName = fileItem.getName();
                        fileName = CommonUtil.getCurrentDateTime() + oldFileName.substring(oldFileName.indexOf("."), oldFileName.length());

                        map.put(fileItem.getFieldName(), sdf.format(new Date())+"/"+fileName);//该参数为生成的文件夹和文件名连在一起
                        createFile(strPhthString);
                        fileItem.write(new File(strPhthString + "/" + fileName));

                    }
                }
            }
            log.error("upload:"+map);
            return map;
        }catch(SizeLimitExceededException e){
            map.clear();
            map.put("error","file to large. The max size is"+size);
        } catch (FileUploadException e) {
            map.clear();
            map.put("error",e.getMessage());
        } catch (IOException e) {
            map.clear();
            map.put("error",e.getMessage());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }

}

 记得引用 commons-fileupload.jar 包,调用方式

  
		        Upload upload = new Upload();

		        String fjid = Identities.uuid2();// 唯一 32位编码
		        upload.setFileName(fjid);
		        int uptype = Upload.FILE;
		        Map map = upload.upload(getRequest() , 0, uptype); //文件删除
			        if (map.isEmpty()) {
				        	setAttr("success", false);
				            setAttr("msg", "未知");
				            renderJson();
			        } else if (map.containsKey("error")) {
			        	   setAttr("success", false);
				           setAttr("msg", ""+ map.get("error") +"");
				           renderJson();
			        }
			//可以将获取的文件真实名称,文件服务器名称,文件路径 ,文件大小 保存数据库        
		        String ext = getFileExt((String) map.get("FILE_NAME"));
		        String wjmc= map.get("FILE_NAME").toString();
		        String path=map.get("FILE_PATH").toString();
		        String archivesfileid= getPara(0);
		        String size=map.get("FILE_SIZE").toString();


你可能感兴趣的:(ajaxFileUpload)