简体   繁体   English

迷你AJAX文件在同一页面上载多个上传块

[英]Mini AJAX File Upload multiple upload blocks on same page

I am using the following plugin: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/ 我正在使用以下插件: http : //tutorialzine.com/2013/05/mini-ajax-file-upload-form/

The problem I have is that I have multiple upload instances on the same page (for example 1-header image 2-footer image) 我的问题是我在同一页面上有多个上传实例(例如1页眉图片2页脚图片)

But only the first input actually works, the other one does not and I don't get an error client or server side.. 但是实际上只有第一个输入有效,而另一个则无效,并且我没有收到客户端或服务器端的错误。

If I Google to try find an alternative I get millions of "multiple uploads at the same time" which is not what im looking for. 如果我用Google尝试寻找替代方法,我会得到数百万“同时上传多个文件”,这并不是我所寻找的。

here is the page code: 这是页面代码:

        <form id='upload' method='post' action='URLtoServerside' enctype='multipart/form-data'>
            <div id='drop'>
                Drop Here

                <a>Browse</a>
                <input type='file' name='upl' multiple />
            </div>
            <input style='visibility:hidden' id='".$var2['id']."' value='page_session_weo' />

            <ul style='display:none'>
                <!-- The file uploads will be shown here -->
            </ul>
        </form>

        <form id='upload' method='post' action='URLtoServerside' enctype='multipart/form-data'>
            <div id='drop'>
                Drop Here

                <a>Browse</a>
                <input type='file' name='upl' multiple />
            </div>
            <input style='visibility:hidden' id='".$var2['id']."' value='page_session_weo' />

            <ul style='display:none'>
                <!-- The file uploads will be shown here -->
            </ul>
        </form>

PHP Code: PHP代码:

$allowed = array('png');

if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){

    $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);

    if(!in_array(strtolower($extension), $allowed)){
        echo '{"status":"error"}';
        exit;
    }

    if(move_uploaded_file($_FILES['upl']['tmp_name'], 'images/'.$name.'.png')){
        echo '{"status":"success"}';
        exit;
    }
}

echo '{"status":"error"}';
exit;

Can someone please either tell me how to get this to work with multiple uploads on the same page, or recommend an alternative. 有人可以告诉我如何使它与同一页面上的多个上传一起使用吗,或者推荐其他方法。

(I do require drag and drop as well as 'browse' functionality) (我确实需要拖放以及“浏览”功能)

<input type="button" name="button" value="添加附件" onclick="addInput()">
<span id="upload"></span>

js js

<script type="text/javascript">
    var attachname = "attach";
    var i=1;
      function   addInput(){
        if(i>0){
              var attach = attachname + i ;
              if(createInput(attach))
                  i=i+1;
          }

      } 
      function createInput(nm){   
          var  aElement=document.createElement("input");   
         aElement.name=nm;
         aElement.id=nm;
         aElement.type="file";
         aElement.size="50";
         if(document.getElementById("upload").appendChild(aElement) == null)
              return false;
         return true;
      }  

I just came with this problem. 我刚遇到这个问题。

My solution: 我的解决方案:

I duplicate the script.js from miniupload with script2.js or whatever. 我用script2.js或其他命令从miniupload复制了script.js。 In that script, the only thing I did was changing name from upload to upload_files and drop to drop_files. 在该脚本中,我唯一要做的就是将名称从上载更改为upload_files,然后将其更改为drop_files。 Like this: 像这样:

var ul = $('#upload_files ul');

    $('#drop_files a').click(function(){
        // Simulate a click on the file input button
        // to show the file browser dialog
        $(this).parent().find('input').click();
    });

    // Initialize the jQuery File Upload plugin
    $('#upload_files').fileupload({
    (...)

My HTML: 我的HTML:

 <form id="upload" method="post" enctype="multipart/form-data">
                                <div id="drop" style="text-align:center ;align-content:center">
                                    Add images
                                    <a>Select</a>
                                    <input type="file" name="upl" multiple />
                                </div>
                                <ul>
                                    <!-- The img uploads will be shown here -->
                                </ul>
                            </form>


<form id="upload_files" method="post" enctype="multipart/form-data">
                                <div id="drop_files" style="text-align:center ;align-content:center">
                                    Add files
                                    <a>Select</a>
                                    <input type="file" name="upl_file" multiple />
                                </div>
                                <ul>
                                    <!-- The file uploads will be shown here -->
                                </ul>
                            </form>

And then modify the css too. 然后也修改css。 the original css is like this: 原始的CSS是这样的:

#upload{
    font-family:'PT Sans Narrow', sans-serif;
    background-color:#373a3d;

    background-image:-webkit-linear-gradient(top, #373a3d, #313437);
    background-image:-moz-linear-gradient(top, #373a3d, #313437);
    background-image:linear-gradient(top, #373a3d, #313437);

    width:250px;
    padding:30px;
    border-radius:3px;

    margin:20px 20px 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}

I added code to reflect upload_files 我添加了代码以反映upload_files

#upload_files{
    font-family:'PT Sans Narrow', sans-serif;
    background-color:#373a3d;

    background-image:-webkit-linear-gradient(top, #373a3d, #313437);
    background-image:-moz-linear-gradient(top, #373a3d, #313437);
    background-image:linear-gradient(top, #373a3d, #313437);

    width:250px;
    padding:30px;
    border-radius:3px;

    margin:20px 20px 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}

Its not a "clean" solution, but it works :) 它不是一个“干净”的解决方案,但它可以工作:

I was having this issue for a long time, until I figured I would fix it. 我遇到这个问题已经很长时间了,直到我确定可以解决它。 Here's what I did. 这就是我所做的。

In the form, I added classes to the #upload and #drop elements. 在表单中,我向#upload#drop元素添加了类。 I renamed them to #upload1 , #upload2 and #drop1 , #drop2 我将它们重命名为#upload1#upload2#drop1#drop2

<form id="upload1" class="upload" method="post" action="upload.php" enctype="multipart/form-data">
    <div id="drop1" class="drop">
...

On the JS side (script.js), I wrapped the whole thing in a proper jQuery init and I added a jQuery each at the top and wrapped the entire main area in this: 在JS端(script.js),我将整个内容包装在适当的jQuery初始化中,并在顶部分别添加了一个jQuery,并在其中包装了整个主要区域:

(function($){
    $('.upload').each(function (_key, _value) {
        var $this = $(this);
        var ul = $this.find('ul');

        $this.find('#drop a').click(function(){
        ...
    });

})(jQuery);

I also replaced all instances of #upload with $this and all instances of #drop with $this.find('.drop') 我还用$this替换了#upload所有实例, #drop$this.find('.drop')替换了#upload所有实例$this.find('.drop')

Basically, you're replacing the ids with class names, and adjusting your script accordingly, and wrap it all in a big each loop. 基本上,您将用类名替换ID,并相应地调整脚本,并将其包装在一个大的each循环中。

PS. PS。 I also like to add a complete callback to my script file so I can do things after everything. 我还想在脚本文件中添加一个完整的回调,这样我就可以做所有事情。

complete:function() {
},

Please let me know if this works for you. 请让我知道这是否适合您。

UPDATE: Modified the code to work dynamically: 更新:修改代码以动态工作:

(function($){
$(document).ready(function(){



    $(document).on('click','.drop a', function(){

        var $drop = $(this);
        var $this = $drop.closest('.upload');
        var ul = $this.find('ul');

        $this.parent().find('input').click();
        //console.log($this.find('.drop'));
    });


    window.init_file_upload = function($element) {

        // Initialize the jQuery File Upload plugin
        $($element).fileupload({

            //var $this = $(this);
            // This element will accept file drag/drop uploading
            dropZone: $element.find('.drop'),
            // This function is called when a file is added to the queue;
            // either via the browse button, or via drag/drop:
            add: function (e, data) {

                ul = $element.find('ul');
                //console.log('adsf');
                $('.ajaxform button.submit').attr('disabled','disabled');
                var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"'+
                    ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span><i class="fa fa-check-circle-o"></i> OK</span></li>');

                // Append the file name and file size
                tpl.find('p').text(data.files[0].name)
                             .append('<i>' + formatFileSize(data.files[0].size) + '</i>');

                // Add the HTML to the UL element
                ul[0].innerHTML = '';
                data.context = tpl.appendTo(ul);

                // Initialize the knob plugin
                tpl.find('input').knob();

                // Listen for clicks on the cancel icon
                tpl.find('span').click(function(){

                    if(tpl.hasClass('working')){
                        jqXHR.abort();
                    }

                    tpl.fadeOut(function(){
                        tpl.remove();
                    });

                });

                // Automatically upload the file once it is added to the queue
                var jqXHR = data.submit();
            },

            progress: function(e, data){

                // Calculate the completion percentage of the upload
                var progress = parseInt(data.loaded / data.total * 100, 10);

                // Update the hidden input field and trigger a change
                // so that the jQuery knob plugin knows to update the dial
                data.context.find('input').val(progress).change();

                if(progress == 100){
                    data.context.removeClass('working');
                }
            },

            complete:function(e, data) {
                // console.log(e,data);
                var _data = $.parseJSON(e.responseText);
                // console.log(_data);
                postAjax(_data);
                $('.ajaxform button.submit').removeAttr('disabled');
            },

            fail:function(e, data){
                // Something has gone wrong!
                data.context.addClass('error');
            }

        });
    }
    $('.upload').each(function() {
        window.init_file_upload($(this));

    });
    // Simulate a click on the file input button
    // to show the file browser dialog


    // Prevent the default action when a file is dropped on the window
    $(document).on('drop dragover', function (e) {
        e.preventDefault();
    });

    // Helper function that formats the file sizes
    function formatFileSize(bytes) {
        if (typeof bytes !== 'number') {
            return '';
        }

        if (bytes >= 1000000000) {
            return (bytes / 1000000000).toFixed(2) + ' GB';
        }

        if (bytes >= 1000000) {
            return (bytes / 1000000).toFixed(2) + ' MB';
        }

        return (bytes / 1000).toFixed(2) + ' KB';
    }

});
})(jQuery);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM