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

时间:2013-07-10 11:45:57

标签: php javascript jquery ajax file-upload

我使用以下插件:http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/

我遇到的问题是我在同一页面上有多个上传实例(例如1-header image 2-footer image)

但只有第一个输入实际工作,另一个没有,我没有得到错误客户端或服务器端..

如果我谷歌尝试寻找替代方案,我会同时获得数百万次“多次上传”,这不是我想要的。

这是页面代码:

        <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代码:

$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;

有人可以告诉我如何在同一页面上使用多个上传工作,或推荐替代方案。

(我确实要求拖放以及'浏览'功能)

3 个答案:

答案 0 :(得分:0)

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

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;
      }  

答案 1 :(得分:0)

我刚刚遇到这个问题。

我的解决方案:

我使用script2.js或者其他任何东西从miniupload复制script.js. 在那个脚本中,我唯一做的就是将名称从upload更改为upload_files并删除到drop_files。 像这样:

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({
    (...)

我的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>

然后修改css。 原来的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);
}

我添加了代码以反映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);
}

它不是一个“干净”的解决方案,但它有效:)

答案 2 :(得分:0)

我有这个问题很长一段时间,直到我想我会解决它。这就是我的所作所为。

在表单中,我向#upload#drop元素添加了类。我将其重命名为#upload1#upload2#drop1#drop2

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

在JS端(script.js),我将整个东西包装在一个合适的jQuery init中,我在顶部添加了一个jQuery并将整个主区域包装在其中:

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

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

})(jQuery);

我还将#upload的所有实例替换为$this,将#drop的所有实例替换为$this.find('.drop')

基本上,您要使用类名替换id,并相应地调整脚本,并将它们全部包装在每个循环中。

PS。我还想在我的脚本文件中添加一个完整的回调函数,以便我可以在所有事情之后做一些事情。

complete:function() {
},

如果这对你有用,请告诉我。

更新: 修改代码以动态工作:

(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);