檔案上傳工具類——傻瓜式上傳檔案

來源:互聯網
上載者:User

標籤:允許   調用   cep   fail   on()   item   tco   upload   tip   

   轉載請註明原文地址:http://www.cnblogs.com/ygj0930/p/6128382.html

   在前面  (http://www.cnblogs.com/ygj0930/p/6073505.html)  我們提到過Javaweb開發的檔案上傳功能的實現,需要藉助第三方jar包,並且要建立factory呀、設定臨時檔案區路徑呀等等,十分繁瑣。而作為一個開發人員,不可能每次實現檔案上傳時都從頭到尾做那麼多工序。這時候,我們可以把這些繁瑣的工作封裝起來,把一個個功能做成以供調用的方法。在我們實現檔案上傳時,只需單純地匯入工具類,然後調用相應的方法即可。因此,我們就有了檔案上傳工具類的構思。

    檔案上傳工具類的實質就是,把繁瑣的工作按照函數塊來封裝,外界通過函數名來調用函數取得結果即可。那麼,我們在檔案上傳過程中,需要用到的常用功能有哪些呢?我這裡的工具類大概實現了以下幾種,還有其他更多的功能讀者可以按需實現:

設定儲存路徑
設定緩衝路徑
設定緩衝大小
設定檔案類型
擷取副檔名
驗證檔案類型有效性
表單內容擷取:文字以索引值對儲存在map中。檔案儲存到儲存目錄下
擷取上傳的檔案內容們(返回map給調用者)

 

   下面是源碼:

    匯入所需的類:

   

import java.util.*;import java.lang.*;import java.io.File;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;

    定義一系列備用的變數、數組、要用到的類對象、工具類的一系列建構函式等

    private String[] fileTypes=null;//允許上傳的檔案類型們    private String dstPath=null;//檔案儲存路徑    private long fileSizeMax=10*1024*1024;//允許上傳的檔案最大值    private String cachePath=null;//緩衝路徑    private int cacheSizeMax=5*1024*1024;//最大緩衝容量    private Map<String,String> textcontent;//上傳表單中的常值內容用map來儲存        private ServletFileUpload sfupload;//實現上傳功能的主要類    private DiskFileItemFactory factory=new DiskFileItemFactory();//定義工廠來配置上傳路徑、緩衝區位置等        public myUploadUtil(){};        public myUploadUtil(String dst,String cache,String[] fileTypes,long fileSizeMax,int cacheSizeMax)    {        super();        this.dstPath=dst;        this.cachePath=cache;        this.fileTypes=fileTypes;        this.fileSizeMax=fileSizeMax;        this.cacheSizeMax=cacheSizeMax;    }        public myUploadUtil(String dst,String cache,String[] fileTypes)    {        super();        this.dstPath=dst;        this.cachePath=cache;        this.fileTypes=fileTypes;    }

    定義setXX()方法供外界調用來設定路徑值、緩衝路徑、檔案類型等等:

public void setCachePath(String cachePath){        this.cachePath=cachePath;    }    public void setCacheSize(int size){        this.cacheSizeMax=size;    }    public void setDstPath(String path){        this.dstPath=path;    }    public void setFileSize(long size){        this.fileSizeMax=size;    }    public void setFileType(String[] types){        this.fileTypes=types;    }

    定義一系列功能方法:擷取內容、判斷檔案類型合法性等等:

//擷取副檔名    public String getFileExt(File file){        String path=file.getName();        return path.substring(path.lastIndexOf(".")+1);    }    //供外界調用擷取上傳表單中的常值內容    public Map<String,String> getTextContent(){        return textcontent;    }    //把提取到的常值內容們賦給類本身的map對象,以供外界取用    public void setTextContent(Map<String,String> map){        this.textcontent=map;    }    //單例模式擷取檔案上傳類,如果不存在則建立,存在則賦給sfuload以免重複建立    public ServletFileUpload getServletFileUpload(){        if(sfupload==null){            sfupload=new ServletFileUpload(factory);            return sfupload;        }else{            return sfupload;        }    }    //判斷檔案是否為合法的類型    public boolean isFileValidate(File file){        if(fileTypes==null){return true;}        for(int i=0;i<fileTypes.length;++i){            if(fileTypes[i].equals(getFileExt(file))){                return true;            }        }        return false;    }    //建立檔案目錄:用於後面根據路徑來建立檔案儲存目錄、緩衝目錄    public void makeDir(String url){                    File file=new File(url);            if(!file.exists()){                if(!file.mkdirs()){                    System.out.println("fail to create dir!");                }            }    }

    最後,定義上傳方法:

//上傳方法    public void upload(HttpServletRequest request){                try{        if(!ServletFileUpload.isMultipartContent(request)){            return;        }        makeDir(dstPath);//建立檔案儲存目錄        makeDir(cachePath);    //建立緩衝目錄        factory.setRepository(new File(cachePath));//設定緩衝路徑        factory.setSizeThreshold(cacheSizeMax);//設定緩衝大小        ServletFileUpload sfu=getServletFileUpload();//擷取上傳類            sfu.setFileSizeMax(fileSizeMax);//設定上傳檔案允許的最大值                    List<FileItem> items=sfu.parseRequest(request);//提取請求中附帶的檔案們        Map<String,String> map =new HashMap<String,String>();//建立一個map對象來提取上傳表單中的常值內容                //迭代提取上傳的檔案們        Iterator it=items.iterator();        while(it.hasNext()){            FileItem  fileItem=(FileItem)it.next();            if(fileItem.isFormField()){//如果是常值內容,則提取出來放進map裡                map.put(fileItem.getFieldName(),fileItem.getString("UTF-8"));            }else{//如果不是文本,則為檔案                String path=fileItem.getName();//擷取檔案名稱                long size=fileItem.getSize();//擷取檔案大小                if ("".equals(path) || size == 0) {//無效檔案的判斷                System.out.println("not validate file");                return;                }                                File file=new File(dstPath,new File(fileItem.getName()).getName());//根據檔案名稱在檔案儲存路徑下建立一個同名檔案                if(!isFileValidate(file)){//判斷檔案類型是否合法                System.out.println("file type incorrect!");                }else{                    fileItem.write(file);//檔案合法,則通過IO流把上傳檔案寫到檔案路徑下                }            }            }        setTextContent(map);//表單常值內容提取完畢,把map中的內容set給類中的textContent對象。        }catch(Exception ex){            System.out.println(ex);        }            }

    使用工具類:

    下面,我們來簡單試試在實際應用中使用我們封裝好的檔案上傳工具類:

   

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><%@page import="java.io.*"%><%@page import="javax.servlet.*"%><%@page import="javax.servlet.http.*"%><%@page import="org.apache.commons.fileupload.servlet.*"%><%@page import="upload.myUploadUtil"%><%    //定義允許上傳的檔案類型    final String allowedExt[] ={"JPG","GIF"};    //擷取web應用在web伺服器上的絕對路徑,用來儲存檔案    String realwebbase = request.getSession().getServletContext().getRealPath("/");    //檔案儲存目錄下建立臨時檔案儲存目錄    String temp_file = realwebbase+"upload\\UploadTemp";        myUploadUtil myupload=new myUploadUtil(realwebbase,temp_file,allowedExt);//建立檔案上傳工具類對象,把檔案儲存路徑等作為參數初始化該對象    myupload.upload(request);//對象調用upload方法實現上傳功能%>

 

   

檔案上傳工具類——傻瓜式上傳檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.