Simple jQuery file upload plugin (using iframe only)

I spent many hours searching the Internet to find a very simple and simple jQuery plugin so that I could upload files without refreshing the page, I didn’t want these big plugins with all their bizarre tricks, and I wanted it to be easy to add to my site. So I just made my own little jQuery plugin, and I decided to share it with all of you if anyone else is looking for it. Now I am not a specialist in creating jQuery plugins, so if there are any improvements I could make, let me know.

So here it is:

This is an html form that you can customize to use it:

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

This is how the plugin is called:

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

This is the plugin itself:

 (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 } } } } 
+4
source share
1 answer

You can use a wonderful bootloader. I use it in a production application and it works very well. We even uploaded it directly to S3.

http://fineuploader.com/

+1
source

Source: https://habr.com/ru/post/1433430/


All Articles