4
我花了很多小時搜索網絡,以找到一個非常簡單和基本的jQuery插件,讓我上傳文件而無需刷新頁面,我不希望這些大插件他們所有的花式技巧,我希望它可以很容易地添加到我的網站。所以我剛剛製作了我自己的小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
}
}
}
}
你能請張貼uploadPhoto.php代碼在這裏,如果你仍然有你嗎?這將是非常有益的。謝謝! – VishwaKumar
我已經添加了'html'和'php' –
我正在尋找相同的東西。事實證明,在iframe中使用獨立的上傳應用程序是最簡單的方法。但我不確定他們是否安全。 – shababhsiddique