4

我花了很多时间在网上搜索一个非常简单和基本的 jQuery 插件,让我可以在不刷新页面的情况下上传文件,我不希望这些大插件具有所有花哨的技术,我希望它可以轻松添加到我的网站。因此,我刚刚制作了自己的小 jQuery 插件,我决定与大家分享它,以防其他人正在寻找它。现在我不是创建 jQuery 插件的专家,所以如果我可以做任何改进,请告诉我。

所以这里是:

这是您可以设置以使用它的 html 表单:

<form enctype="multipart/form-data" class="fileUpload">
    <input type="file" name="uploadFile" />
</form>

这是插件的调用方式:

$("body").on("change", ".fileUpload", function(){   

    $(this).fileUpload({
        form: $(this), //selector of the form 
        actionURL: "uploadPhoto.php", //directory to handle upload
        success: function(html){
            //on successful upload, in this case if there is any html returned
            $("body").prepend(html);

        }, 
        error: function(){          

        }   
    }); 
});

这是插件本身:

(function($){
    $.fn.extend({

        fileUpload: function(options) {

            var defaults = {
               form: null,
               actionURL: null,
               success: function(){},
               error: function(){},
            };

            var options = $.extend(defaults, options);

            return this.each(function() {

                $('<iframe />', {
                id: 'upload_iframe',
                name: 'upload_iframe',
                style: 'width:0; height:0; border:none;'
                }).appendTo('body');    

                var form = $(options.form);
                form.attr("action", options.actionURL);
                form.attr("method", "post");
                form.attr("enctype", "multipart/form-data");
                form.attr("encoding", "multipart/form-data");
                form.attr("target", "upload_iframe");
                form.submit();


                $("#upload_iframe").load(function () {
                    html = $("#upload_iframe")[0].contentWindow.document.body.innerHTML;

                    html!='' ? options.success.call(this, html) : options.error.call(this);

                    $("iframe#upload_iframe").remove();

                }); 


            });
        }
    });
})(jQuery);

上传照片.php:

foreach($_FILES as $file)
{

    foreach ($file['uploadFile'] as $name)
    {

    $fileArr = explode("." , $name);
    $ext = strtolower($fileArr[count($fileArr)-1]);
    $allowed = array("jpg", "jpeg", "png", "gif", "bmp");

        if(in_array($ext, $allowed))
        {
            $source = $file['tmp_name'][$i++];
            $path = "images/";
            $filename = uniqid();

            if (move_uploaded_file($source, $path.$filename.$ext))
            {
            //Do whatever on success of file upload 
            }
        }       
    }
}
4

1 回答 1

1

您可以使用精细的上传器。我在生产应用程序中使用它并且效果很好。我们甚至可以将其直接上传到 S3。

http://fineuploader.com/

于 2013-10-13T08:16:23.000 回答