Javascript 同一页面上的多个Ajax Uploader实例

Javascript 同一页面上的多个Ajax Uploader实例,javascript,ajax,file-upload,multiple-instances,instances,Javascript,Ajax,File Upload,Multiple Instances,Instances,我开发了一个ajax文件上传器,如果页面上有一个实例,它就可以工作得很好。我尝试将其转换为允许多个实例,它几乎可以工作,除了在一个表单中上载多个文件时,它可以很好地上载第一个文件,但是对于所有后续文件,出于某种原因,它指向第二个表单实例的下一个文件读取器。如果我使用上传表单的最后一个(第二个)实例上传,多个文件可以上传。但是,如果我尝试使用第一个实例上载,它将上载第一个文件,但所有后续文件都会从第二个实例发送到空文件输入。我不明白为什么。我在上传表单中使用唯一id名称,并在javascript函

我开发了一个ajax文件上传器,如果页面上有一个实例,它就可以工作得很好。我尝试将其转换为允许多个实例,它几乎可以工作,除了在一个表单中上载多个文件时,它可以很好地上载第一个文件,但是对于所有后续文件,出于某种原因,它指向第二个表单实例的下一个文件读取器。如果我使用上传表单的最后一个(第二个)实例上传,多个文件可以上传。但是,如果我尝试使用第一个实例上载,它将上载第一个文件,但所有后续文件都会从第二个实例发送到空文件输入。我不明白为什么。我在上传表单中使用唯一id名称,并在javascript函数中引用该唯一id。我将尝试在下面包含所有必要的代码位

表单由PHP生成。php var
$uid
是一个随机生成的唯一id,我一直在使用它。首先,上传功能的初始化输出到
标签中的页面:

'<script> '.
    'jQuery(document).ready(function($){ '.
        'var myup_'.$uid.' = new MyUp({ '.
            'form_id: "myup_form_'.$uid.'", '.
            'uid: '.$uid.', '.
            'container: "'.$name.'", '.
            'table: "'.$style.'", '.
            'iconcolor: "'.$iconcolor.'", '.
            'maxsize: '.$maxsize.', '.
            'permitted: '.$permitted.', '.
            'prohibited: '.$prohibited.', '.
            'fixed: '.$fixedsetting.', '.
            'pathcheck: "'.$pathcheck.'", '.
            'uploader: '.$uploader.', '.
            'loading: "'.my_url.'/lib/img/ajax.gif" '.
        }); '.
    '}); '.
'</script>';
''。
'jQuery(document).ready(函数($){'。
'var myup.'$uid.'=新的myup({'。
'form_id:'myup_form_.'$uid.','。
“uid:”.$uid.,”。
“容器:”。$name.“,”。
'表格:'.$style'.','。
“iconcolor:”.$iconcolor.“,”。
“maxsize:”.$maxsize.,”。
“允许:”.$允许。”,“。
'禁止:'.$禁止','。
“已修复:”.$fixedsetting.,”。
“路径检查:”.$pathcheck.“,”。
'上传者:'.$uploader.','。
'加载:'.my_url./lib/img/ajax.gif'。
}); '.
'}); '.
'';
显然,我的设置的所有这些变量都是在前面定义的。当页面上有多个实例时,它会正确读取每个不同实例的设置。它们以不同的样式、图标颜色、文件类型权限、最大文件大小设置等成功显示。所有这些都适用于多个实例

现在填写表格:

'<div class="myup_container" style="'.$inlinestyle.'">'.
    '<form name="myup_form_'.$uid.'" id="myup_form_'.$uid.'" action="javascript:void(0);" enctype="multipart/form-data">'.
        '<input type="hidden" id="upload-actionpath-'.$uid.'" value="'.$fixed.'" data-basename="'.$basename.'" data-start="'.$start.'" />'.
        '<div class="myup_buttons_container" style="text-align:right;">'.
            '<span class="myup_wrapper" style="text-align:left;">'.
                '<input type="file" name="myup_files_'.$uid.'[]" id="myup_files_'.$uid.'" class="hidden_browse"'.$multiple.' />'.
                '<span class="add_files">'.$addfiles.'</span>'.
                '<span id="submit_upload_'.$uid.'">'.$uploadlabel.'</span>'.
            '</span>'.
        '</div>'.
    '</form>'.
    '<div id="myup_files_container_'.$uid.'" class="myup_files_container"></div>'.
    '<span id="my_removedfiles_'.$uid.'" style="display:none;"></span>'.
'</div>';
''。
''.
''.
''.
''.
''.
“.$addfiles.”。
“.$uploadlabel.”。
''.
''.
''.
''.
''.
'';
这是一个精简版。脚本标记中包含设置的实例和html表单由短代码输出。因此,页面上的多个短代码将输出MyUp函数的多个实例

下面是我希望的javascript函数的所有相关部分(很长,抱歉,但我删除了大量内容):

jQuery(文档).ready(函数($)
{
//在整个过程中,var fuid将引用
//从html表单和实例设置返回php var$uid
函数myupRemove(id、文件名、fuid)
{
//处理用户从输入字段中删除的文件
//在提交上传之前
}
函数MyUp(配置)
{
this.settings=config;
this.fuid=this.settings.uid;
this.file=“”;
this.browsed_files=[];
var self=这个;
MyUp.prototype.myupDisplay=函数(值)
{
this.file=值;
如果(this.file.length>0)
{
/*这是一段非常长的代码
*我会饶了你,但基本上我是迭代的
*通过输入字段中的所有文件
*并将它们动态地放入表中
*把桌子放在书页上
*因此用户可以重命名它们,在上载之前删除它们,
*然后在上传文件时查看每个文件的状态栏。
*这部分代码可以很好地处理多个实例。
*/
}
}
//创建唯一ID
MyUp.prototype.uid=函数(名称)
{
//这里我为每个文件生成一个唯一的ID,
//并在其前面加上实例的唯一id(即this.fuid)
返回此.fuid+''name.replace(/[^a-z0-9\s]/gi,'''.'').replace(/[\s]/g,''.');
}           
//获取文件扩展名
MyUp.prototype.ext=函数(文件,小写)
{
返回(/[.]/.exec(file))?(小写?/[^.]+$/.exec(file.toLowerCase()):/[^.]+$/.exec(file)):“”;
}
//格式化文件大小
MyUp.prototype.nicesize=函数(文件大小)
{
//一堆代码来格式化文件大小,然后。。。
返回大小;
}
//属性文件类型图标
MyUp.prototype.icon=函数(图标外部,颜色)
{
//要确定的一组数组
//要在表中显示的文件类型图标
}
//文件读取器
MyUp.prototype.read=函数(e)
{
if(例如target.files)
{
//引用myupDisplay函数
//将文件添加到表中的位置
self.myupDisplay(e.target.files);
self.browsed_files.push(e.target.files);
} 
}
功能加法器(类型、el、fn)
{
if(window.addEventListener)
{
el.addEventListener(类型,fn,错误);
} 
else if(窗口附件)
{
var f=函数()
{
fn.呼叫(el、窗口、事件);
};          
el.attachEvent('on'+类型,f)
}
}
//收集文件ID并启动上载以提交
MyUp.prototype.starter=函数()
{
if(window.File&&window.FileReader&&window.FileList&&window.Blob)
{
var browsed_file_id=$(“#”+this.settings.form_id).find(“输入[type='file']”)eq(0).attr(“id”);
document.getElementById(已浏览的文件id).addEventListener('change',this.read,false);
document.getElementById('submit_upload_uu'+this.fuid.).addEventListener('click',this.submit,true);
} 
else警报(浏览器无法读取消息);
}
//点击开始上传
MyUp.prototype.submit=函数()
{ 
自我保护
jQuery(document).ready(function($)
{
// throughout, the var fuid will refer 
// to the php var $uid from the html form and instance settings

function myupRemove(id, filename, fuid)
{
    // handle files the user removes from the input field 
    // before submitting the upload
}
function MyUp(config)
{
    this.settings = config; 
    this.fuid = this.settings.uid;
    this.file = ""; 
    this.browsed_files = []; 
    var self = this;
    MyUp.prototype.myupDisplay = function(value)
    {
        this.file = value;
        if(this.file.length > 0)
        {
            /* this is a really long bit of code
             * that i'll spare you, but basically I iterate 
             * through all the files in the input field
             * and put them dynamically into a table 
             * and drop the table onto the page
             * so the user can rename them, remove them before upload,
             * and then watch the status bar for each file as it uploads.
             * This portion of the code works fine with multiple instances.
            */
        }
    }
    // Create Unique ID
    MyUp.prototype.uid = function(name)
    {
        // Here I generate a unique ID for each file, 
        // and prepend it with the Instance's unique id (i.e., this.fuid)
        return this.fuid+'_'+name.replace(/[^a-z0-9\s]/gi, '_').replace(/[_\s]/g, '_');
    }           
    // Get File Extension
    MyUp.prototype.ext = function(file, lowercase)
    {
        return (/[.]/.exec(file)) ? (lowercase ? /[^.]+$/.exec(file.toLowerCase()) : /[^.]+$/.exec(file)) : '';
    }
    // Format File Size
    MyUp.prototype.nicesize = function(fileSize)
    {
        // a bunch of code to format the file size then...
        return niceSize;
    }
    // Attribute FileType Icons
    MyUp.prototype.icon = function(icon_ext, color)
    {
        // a bunch of arrays to determine 
        // which file type icon to display in the table
    }
    //File Reader
    MyUp.prototype.read = function(e) 
    {
        if(e.target.files) 
        {
            // references the myupDisplay function 
            // where I add the files to a table
            self.myupDisplay(e.target.files);
            self.browsed_files.push(e.target.files);
        } 
    }
    function addEvent(type, el, fn)
    {
        if(window.addEventListener)
        {
            el.addEventListener(type, fn, false);
        } 
        else if(window.attachEvent)
        {
            var f = function()
            {
              fn.call(el, window.event);
            };          
            el.attachEvent('on' + type, f)
        }
    }
    // Collect File IDs and Initiate Upload for Submit
    MyUp.prototype.starter = function() 
    {
        if(window.File && window.FileReader && window.FileList && window.Blob) 
        {

            var browsed_file_id = $("#"+this.settings.form_id).find("input[type='file']").eq(0).attr("id");
            document.getElementById(browsed_file_id).addEventListener('change', this.read, false);
            document.getElementById('submit_upload_'+this.fuid).addEventListener('click', this.submit, true);
        } 
        else alert(browser_cant_read_message);
    }
    // Begin Upload on Click
    MyUp.prototype.submit = function()
    { 
        self.begin(); 
    }
    // Initiate Upload Iterator
    MyUp.prototype.begin = function() 
    {
        if(this.browsed_files.length > 0)
        {
            for(var k=0; k<this.browsed_files.length; k++)
            {
                var file = this.browsed_files[k];
                this.myupAjax(file,k);
            }
            this.browsed_files = [];
        }
        else alert(no_files_chosen_message);
    }
    // Ajax Upload
    MyUp.prototype.myupAjax = function(file,i)
    {
        if(file[i]!== undefined)
        {
            var id = file_id = self.uid(file[i].name),
                rawname = file[i].name.substr(0, file[i].name.lastIndexOf('.')) || file[i].name,
                extension = self.ext(file[i].name, false),
                browsed_file_id = $("#"+this.settings.form_id).find("input[type='file']").eq(0).attr("id");
                path = this.settings.fixed ? this.settings.fixed : String($('input#upload-actionpath-'+this.fuid).val()),
                pathcheck = String(this.settings.pathcheck),
                removed_file = $("#"+id).val(),
                newname = String($('input#rename_upfile_id_'+id).val()),
                new_name = newname === '' || newname === 'undefined' || newname === undefined ? file[i].name : newname+'.'+extension,
                removed = this.settings.removed,
                loading = this.settings.loading,
                fixedchars = this.settings.fixed;
            // if the file is removes, skip to the next file
            if(removed_file !== '' && removed_file !== undefined && removed_file == id) self.myupAjax(file,i+1); 
            else
            {
                var myupData = new FormData();
                myupData.append('upload_file',file[i]);
                myupData.append('upload_file_id',id);
                myupData.append('max_file_size',this.settings.maxsize);
                myupData.append('upload_path',path);    
                myupData.append('new_name',new_name);
                myupData.append('extension',extension);
                myupData.append('uploader',this.settings.uploader);
                myupData.append('act','upload');
                myupData.append('nonce',myup.nonce);                
                $.ajax(
                {
                    type        : 'POST',
                    url         : myup.ajaxurl+'?action=myup-uploads',
                    data        : myupData,
                    id          : id,
                    fuid        : this.fuid,
                    new_name    : new_name,
                    rawname     : rawname,
                    extension   : extension,
                    path        : path,
                    pathcheck   : pathcheck,
                    removed     : removed,
                    loading     : loading,
                    fixedchars  : fixedchars,
                    cache       : false,
                    contentType : false,
                    processData : false,
                    beforeSend  : function(xhr, settings)
                    {
                        // I added this alert because it shows me that when I'm using the first instance
                        // after the first file uploads, it starts looking to the file input field 
                        // from the second instance
                        alert('path: '+settings.path+' pathcheck: '+settings.pathcheck);

                        // in here I do a bunch of security stuff before uploading
                    },
                    xhr: function()
                    {
                        // my progress bar function here
                    },
                    success : function(response)
                    {
                        setTimeout(function()
                        {
                            if(response.indexOf(id) != -1)
                            {
                                // do success stuff, like green checkmark, remove table row, etc.
                            }
                            else
                            {
                                // do failure stuff, like red x and error message
                            }

                            // AND HERE IS THE IMPORTANT PART
                            // THIS SAYS TO GO ON TO THE NEXT FILE IN THE ARRAY
                            // BUT WHEN USING THE FIRST INSTANCE
                            // IT SENDS US TO THE SECOND INSTANCE'S FILE READER
                            // if I'm uploading with the second form it's fine
                            if(i+1 < file.length) self.myupAjax(file,i+1); 
                        },500);
                    }
                });
             }
        }
    }   
    this.starter();
}
window.MyUp = MyUp;
window.myupRemove = myupRemove;
});
function MyUp(config) {
    /// ...
    var self = this;
    MyUp.prototype.foo = function() {
        // use `self`
    };
}
function MyUp(config) {
    /// ...
}
MyUp.prototype.foo = function() {
    // use `this`
};
(function() {
   var uploadsInProgress = 0;

   // declare MyUp and use uploadsInProgress; it will be hidden from customer code

   window.MyUp = MyUp;
})();