FLASH圖片上傳功能—從百度編輯器UEditor里面提取出來


為了記錄工作中碰到的各種問題,以及學習資料整理,今天開始,將以往的文章進行了一個整理,以后也開始認真的記錄學習過程中的各種問題


在HTML里面的文件上傳功能一直是個問題,為了實現上傳文件大小限制,怎樣顯示進度條問題,以及上傳前圖片預覽,也試過各種辦法,直到有一天看到百度編輯器中的圖片上傳功能。花了點功夫把他單獨提取出來。


最終效果圖如下:

 

 

 

這個功能可以提供多個圖片文件選擇,預覽,然后對上傳的圖片在上傳隊列中刪除,以及旋轉和,上傳中進度條顯示,以及上傳相冊的選擇。

源代碼下載路徑為: http://pan.baidu.com/s/13iNYw

結構

1:FLASH文件:imageUploader.swf

用來顯示上傳隊列,並提供圖片增加,預覽,刪除,旋轉,以及進度條的顯示功能!

包括了一些參數設置,例如上傳處理程序,以及相關的屬性設置。其中最重要參數為:flashvars, 他的值經過URL編碼。

URL編碼轉換功能,你可以通過http://tool.chinaz.com/Tools/URLEncode.aspx 這個工具實現。

原始值為:

container=flashContainer&url=/BaiduUE/imageUp&ext={"param1":"value1", "param2":"value2"}&fileType={"description":"圖片", "extension":"*.gif;*.jpeg;*.png;*.jpg"}&flashUrl=imageUploader.swf&width=608&height=272&gridWidth=121&gridHeight=120&picWidth=100&picHeight=100&uploadDataFieldName=upfile&picDescFieldName=pictitle&maxSize=4&compressSize=2&maxNum=32&compressSide=0&compressLength=900

備注

  • container:"flashContainer", //flash容器id
  • url:"/BaiduUE/imageUp", // 上傳處理頁面的url地址
  • ext:'{"param1":"value1", "param2":"value2"}', //可向服務器提交的自定義參數列表
  • fileType:'{"description":"圖片", "extension":"*.gif;*.jpeg;*.png;*.jpg"}', //上傳文件格式限制
  • flashUrl:'imageUploader.swf', //上傳用的flash組件地址
  • width:608, //flash的寬度
  • height:272, //flash的高度
  • gridWidth:121, // 每一個預覽圖片所占的寬度
  • gridHeight:120, // 每一個預覽圖片所占的高度
  • picWidth:100, // 單張預覽圖片的寬度
  • picHeight:100, // 單張預覽圖片的高度
  • uploadDataFieldName:"upfile", // POST請求中圖片數據的key
  • picDescFieldName:'pictitle', // POST請求中圖片描述的key
  • maxSize:4, // 文件的最大體積,單位M
  • compressSize:2, // 上傳前如果圖片體積超過該值,會先壓縮,單位M
  • maxNum:32, // 單次最大可上傳多少個文件
  • compressSide:0, //等比壓縮的基准,0為按照最長邊,1為按照寬度,2為按照高度
  • compressLength:900 //能接受的最大邊長,超過該值Flash會自動等比壓縮

2:JS腳本

用來於處理外部相冊選擇,以及FLASH事件相應,以及調用FLASH上傳功能來實現圖片上傳

/***********************Flash事件*****************************/
/**
* 檢查flash狀態
* @private
* @param {Object} target flash對象
* @return {Boolean}
*/
function _checkReady(target) {
    if (typeof target !== 'undefined' && typeof target.flashInit !== 'undefined' && target.flashInit()) {
        return true;
    } else {
        return false;
    }
}
/**
* 創建一個隨機的字符串
* @private
* @return {String}
*/
function _createString() {
    var prefix = 'mw__flash__';
    return prefix + Math.floor(Math.random() * 2147483648).toString(36);
}

/**
* 為傳入的匿名函數創建函數名
* @private
* @param {String|Function} fun 傳入的匿名函數或者函數名
* @return {String}
*/
function _createFunName(fun) {
    var name = '';
    name = _createString();
    window[name] = function () {
        fun.apply(window, arguments);
    };
    return name;
}
/***
反復判斷Flash是歐加載完成,完成后為Flash添加回調函數..
*/
var interval = setInterval(function () {
    try {
        var flash = thisMovie("flash");
        if (_checkReady(flash)) {               //輪詢flash的某個方法即可

            var callBack = [];
            callBack[0] = _createFunName(selectFileCallback);
            callBack[1] = _createFunName(exceedFileCallback);
            callBack[2] = _createFunName(deleteFileCallback);
            callBack[3] = _createFunName(StartUploadCallback);
            callBack[4] = _createFunName(uploadCompleteCallback);
            callBack[5] = _createFunName(uploadErrorCallback);
            callBack[6] = _createFunName(allCompleteCallback);
            callBack[7] = _createFunName(changeHeightCallback);
            thisMovie("flash").call('setJSFuncName', [callBack]);

            clearInterval(interval);
        }
    }
    catch (ex) {
    }
}, 20);

//獲得Flash對象
function thisMovie(movieName) {
    if (navigator.appName.indexOf("Misrosoft") != -1) {
        return window[movieName];
    }
    else {
        return document[movieName];
    }
}

 

3:一般處理程序:Upload.ashx

用來實現ASP.NET圖片服務器保存

    string state = "SUCCESS";

    string URL = null;
    string currentType = null;
    string uploadpath = null;
    string filename = null;
    string originalName = null;
    HttpPostedFile uploadFile = null;
    
    public void ProcessRequest (HttpContext context) {        
        context.Response.ContentType = "text/plain";
        context.Response.Write(UploadPoto(context));
    }


    #region 照片上傳
    public string UploadPoto(HttpContext context)
    {
        int aid = Convert.ToInt32(context.Request.Form["aid"]);     //獲得相冊ID
        bool mark = Convert.ToString(context.Request.Form["mark"]).ToLower() == "true";     //獲得是否有水印
        //上傳配置
        string pathbase = "Upload/" + aid.ToString();      //保存路徑
        int size = 2;           //文件大小限制,單位MB  
        string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };         //文件允許格式


        //上傳圖片
        Hashtable info = new Hashtable();
        info = upFile(context,pathbase, filetype, size, mark);                               //獲取上傳狀態

        string title = getOtherInfo(context,"pictitle");                              //獲取圖片描述

        string oriName = getOtherInfo(context,"fileName");                //獲取原始文件名

        string ret = "{'url':'" + info["url"] + "','title':'" + title + "','original':'" + oriName + "','state':'" + info["state"] + "'}";
        return ret;
    }



    private Hashtable upFile(HttpContext context,string pathbase, string[] filetype, int size, bool mark)
    {
        pathbase = pathbase + "/";
        uploadpath = context.Server.MapPath(pathbase);//獲取文件上傳路徑

        try
        {
            uploadFile = context.Request.Files[0];
            originalName = uploadFile.FileName;

            //目錄創建
            createFolder();

            //格式驗證
            if (checkType(filetype))
            {
                state = "不允許的文件類型";
            }
            //大小驗證
            if (checkSize(size))
            {
                state = "文件大小超出網站限制";
            }
            //保存圖片
            if (state == "SUCCESS")
            {
                filename = reName();
                string smallPath = reSmallName();
                string waterPath = rePicName();

                uploadFile.SaveAs(uploadpath + filename);

                string savePath = uploadpath + filename;
                ImageClass imageClass = new ImageClass();
                if (imageClass.ShowThumbnail(savePath, uploadpath + smallPath, 640))     //如果有小圖,則刪除原圖
                {
                    FileInfo fi = new FileInfo(savePath);
                    fi.Delete();
                    URL = pathbase + smallPath;
                    filename = smallPath;
                }
                else
                {
                    URL = pathbase + filename;
                }
                if (mark)
                {
                    string watxt = "我是水印哈。。。";
                    if (ImageClass.WriterText(uploadpath + filename, uploadpath + waterPath, watxt))
                    {
                        URL = pathbase + waterPath;
                        filename = waterPath;
                    }
                }

            }
        }
        catch (Exception e)
        {
            state = "未知錯誤";
            URL = "";
        }
        return getUploadInfo();
    }
    #endregion
    #region 上傳文件的輔助方法

    /**
    * 獲取文件信息
    * @param context
    * @param string
    * @return string
    */
    protected string getOtherInfo(HttpContext context,string field)
    {
        string info = null;
        if (context.Request.Form[field] != null && !String.IsNullOrEmpty(context.Request.Form[field]))
        {
            info = field == "fileName" ? context.Request.Form[field].Split(',')[1] : context.Request.Form[field];
        }
        return info;
    }
    /**
     * 獲取上傳信息
     * @return Hashtable
     */
    protected Hashtable getUploadInfo()
    {
        Hashtable infoList = new Hashtable();

        infoList.Add("state", state);
        infoList.Add("url", URL);

        if (currentType != null)
            infoList.Add("currentType", currentType);
        if (originalName != null)
            infoList.Add("originalName", originalName);
        return infoList;
    }
    /**
     * 重命名文件
     * @return string
     */
    protected string reName()
    {
        return System.Guid.NewGuid() + getFileExt();
    }
    protected string reSmallName()
    {
        return System.Guid.NewGuid() + "_Small" + getFileExt();
    }
    protected string rePicName()
    {
        return System.Guid.NewGuid() + "_poto" + getFileExt();
    }
    /**
     * 文件類型檢測
     * @return bool
     */
    protected bool checkType(string[] filetype)
    {
        currentType = getFileExt();
        return Array.IndexOf(filetype, currentType) == -1;
    }

    /**
     * 文件大小檢測
     * @param int
     * @return bool
     */
    protected bool checkSize(int size)
    {
        return uploadFile.ContentLength >= (size * 1024 * 1024);
    }
    /**
    * 獲取文件擴展名
    * @return string
    */
    protected string getFileExt()
    {
        string[] temp = uploadFile.FileName.Split('.');
        return "." + temp[temp.Length - 1].ToLower();
    }

    /**
     * 按照日期自動創建存儲文件夾
     */
    protected void createFolder()
    {
        if (!Directory.Exists(uploadpath))
        {
            Directory.CreateDirectory(uploadpath);
        }
    }
    #endregion

 

更詳細的內容請參考源代碼 ,對於有童鞋說不支持Chrome,我想應該是Flash的HTML編碼問題,最近較忙,就不花時間去處理了。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM