jquery jQuery-File-Upload 例子

網上jquery-file-upload的例子 都過於簡單,在項目中這個插件經常使用,寫個例子供參考。

下面介紹 用插件實現圖片異步上傳的代碼。


1 比要的js一個都不能少,他們之間是有依賴關係的。

jquery-1.8.2.min.js
jquery.ui.core.js
jquery.ui.widget.js
jquery.fileupload.js
jquery.iframe-transport.js
jquery.fileupload-process.js
jquery.fileupload-validate.js
(最後2個js是有依賴的,缺少的話acceptFileTypes,maxFileSize 不會進行驗證)

2 貼代碼:
[code]
<script>
$(function () {

uploadImageAjaxDelete = function (url,obj){
$.ajax({url:url,async:false,dataType:"text",success:function(data){
if(data=='1'){
//如果刪除成功,恢復file的使用,同時是圖片漸變消失
$(obj).parent().children("input[type='file']").removeAttr("disabled");
$(obj).parent().children("img").fadeOut("slow",function(){
$(this).add($(obj).parent().children("a")).add($(obj).parent().children("input:hidden")).add($(obj).parent().children("br")).remove();
});
}else{
alert('圖片刪除失敗!');
}
}});
}

$("input[type='file']").fileupload({
url: 'image_ajax_save.action',
dataType: 'json',
autoUpload: true,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 2097152// 2 MB
}).on('fileuploadadd', function (e, data) {
$(this).parent().children("label").remove();
$("<p class='uploadImgLoad'>上傳中... 0%</p>").appendTo($(this).parent());
$(this).attr("disabled",true);
}).on('fileuploadprocessalways', function (e, data) {
if(data.files.error){
$(this).parent().children("p").remove();
$(this).removeAttr("disabled");
if(data.files[0].error=='acceptFileTypes'){
$(this).parent().append("<label class='error'>圖片類型錯誤</label>");
}
if(data.files[0].error=='maxFileSize'){
$(this).parent().append("<label class='error'>圖片不能大於2M</label>");
}
}
}).on('fileuploadprogressall', function (e, data) {
var $p = $(this).parent().children("p");
var progress = parseInt(data.loaded / data.total * 100, 10);
if($p.length==0){
$("<p class='uploadImgLoad'>上傳中... "+progress+"%</p>").appendTo($(this).parent());
}else{
console.info(progress);
$p.text('上傳中... '+progress+'%');
if(progress==100){
$p.fadeOut("slow",function(){
$(this).remove();
});
}
}
}).on('fileuploaddone', function (e, data) {
if(data.result.result=='error'){
$(this).removeAttr("disabled");
alert('抱歉,上傳過快,請稍等!');
}else if(data.result.result=='success'){
$(this).parent().prepend($("<a href='#' > 刪除</a>").attr("onclick","uploadImageAjaxDelete('image_ajax_delete.action?dbFileName="+data.result.dbFileName+"',this)").add("<br/>"))
.prepend($("<img width='140' height='90' border='0' />").attr("src",data.result.url))
.prepend($("<input type='hidden' name="+data.result.hiddenName+" id="+data.result.hiddenName+" value='"+data.result.dbFileName+"' />"));
}
});


});

</script>
[/code]

3效果:見附件圖片。


4 注意:操作的時候一定查看:API,Demo
https://github.com/blueimp/jQuery-File-Upload/wiki/API
http://blueimp.github.io/jQuery-File-Upload/basic.html

此外 fireFox 的 debug插件配合使用,有腳本輸出的斷點功能,以及console.info的顯示。

在使用中如有問題,請給我留言,共同探討..進步。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章