简单的jQuery文件上传插件(仅使用iframe)

时间:2012-09-10 17:49:42

标签: jquery jquery-plugins file-upload

我花了很多时间在网上搜索一个非常简单和基本的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);

uploadPhoto.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 
            }
        }       
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用精细上传器。我在生产应用程序中使用它并且它运行良好。我们甚至将它直接上传到S3。

http://fineuploader.com/