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

我花了很多时间在网上搜索找到一个非常简单和基本的jQuery插件,允许我上传文件而不刷新页面,我不想要这些大插件的所有花哨的技术,我希望它很容易添加到我的网站。 所以我刚刚创建了自己的小jQuery插件,我决定与大家分享,以防其他人在寻找。 现在我不是创建jQuery插件的专家,所以如果我有任何改进,请告诉我。

所以这里是:

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

这是插件的调用方式:

 $("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() { $('', { 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 } } } } 

您可以使用精细上传器。 我在生产应用程序中使用它,它工作得很好。 我们甚至将它直接上传到S3。

http://fineuploader.com/