異步上傳文件、圖片

// 目標頁面上有東西 <input type="file" name="fileField" id="fileField" />
function ajaxUpload(opt) {

    /*
    參數說明:
    opt.ID : 頁面裏file控件的ID;
    opt.Format : 文件格式,以數組的形式傳遞,如['jpg','png','gif','bmp'];
    opt.CallBack : 上傳成功後回調;
    opt.Url:上傳地址;
    opt.ImageSizeArry:圖片壓縮尺寸,如['200x200','100x100'];
    opt.ProxyUrl : 上傳回調代理地址
    */
    var iName = "frameName" + Math.random().toString(); //太長了,變短點
    var iframe, form, file, fileParent;

    var postUrl = opt.Url;
    if (postUrl.indexOf("?") <= -1)
    {
        postUrl += "?rd=" + Math.random();
    }

    if (opt.ImageSizeArry != null && opt.ImageSizeArry != undefined && opt.ImageSizeArry != "") {
        postUrl += "&ImageSizeArry=" + opt.ImageSizeArry;
    }

    if (opt.ProxyUrl != null && opt.ProxyUrl != undefined && opt.ProxyUrl != "") {
        postUrl += "&proxyUrl=" + encodeURIComponent(opt.ProxyUrl);
    }

    //建立iframe和form表單
    iframe = $('<iframe name="' + iName + '" style="display:none;"  />');
    form = $('<form method="post" target="' + iName + '" style="display:none;" action="' + postUrl + '"  name="form_' + iName + '" enctype="multipart/form-data" ></from>');
    file = $('#' + opt.ID); //經過ID獲取flie控件
    fileParent = file.parent(); //存父級

    if (file.val()=="") {
        return;
    }

    file.appendTo(form);
    //插入body
    $(document.body).append(iframe).append(form);

    //取得所選文件的擴展名
    var fileFormat = /\.[a-zA-Z]+$/.exec(file.val())[0].substring(1);
    if (opt.Format.join('-').indexOf(fileFormat) != -1) {
        form.submit(); //格式經過驗證後提交表單;

    } else {
        file.appendTo(fileParent); //將file控件放回到頁面
        iframe.remove();
        form.remove();
        $.DR_Alter("文件格式錯誤,請從新選擇!");
    };

    //文件提交完後
    iframe.load(function () {
        var data = $(iframe).contents().find('body').html();
        file.appendTo(fileParent);
        iframe.remove();
        form.remove();
        opt.CallBack(data, opt.ID);
    })


}
相關文章
相關標籤/搜索