公司項目目前用到了webuploader插件,目前就寫一下我所遇到的下問題,其實用法也很簡單,下面貼出我的代碼
因為只是一個上傳文件插件,而我們用到的也就是上傳圖片的功能,它的唯一缺點就是沒有回顯服務端穿過來的圖片,導致每次關閉頁面之后再次進來,上次上傳的圖片就不存在,所以我寫了一個回顯的代碼。這里只是一張,后面若是你們遇到多張的可以循環一下,特殊說明下,下面紅色標出的是判斷圖片為空的話就不現實img,否則老是占位影響效果。(因為用的beetl模板所以直接也i按做了判斷)
<div id="uploader" class="wu-example">
<div class="imgShow"><!--回顯服務端圖片-->
@if(!isEmpty(item.fileRealPath)){
<img src="${item.fileRealPath!}"/>
@}
<div class="file-panels">
<span class="cancel btn-cancel">刪除</span>
</div>
</div>
<div class="queueList">
<div id="dndArea" class="placeholder">
<input type="hidden" id="productKey" value="${item.productKey}">
<div id="filePicker"></div>
<!--<p>或將照片拖到這里,單次最多可選300張</p>-->
</div>
</div>
<div class="statusBar" style="display:none;">
<div class="progress">
<span class="text">0%</span>
<span class="percentage"></span>
</div>
<div class="info"></div>
<div class="btns">
<div id="filePicker2"></div>
<div class="uploadBtn">開始上傳</div>
</div>
</div>
</div>
下面是相應的js,而下面標紅的就是我ajax提交前傳參數給服務端的寫法
jQuery(function() {
var $ = jQuery,
$wrap = $('#uploader'),
// 圖片容器
$queue = $('<ul class="filelist"></ul>')
.appendTo( $wrap.find('.queueList') ),
// 狀態欄,包括進度和控制按鈕
$statusBar = $wrap.find('.statusBar'),
// 文件總體選擇信息。
$info = $statusBar.find('.info'),
// 上傳按鈕
$upload = $wrap.find('.uploadBtn'),
// 沒選擇文件之前的內容。
$placeHolder = $wrap.find('.placeholder'),
// 總體進度條
$progress = $statusBar.find('.progress').hide(),
// 添加的文件數量
fileCount = 0,
// 添加的文件總大小
fileSize = 0,
// 優化retina, 在retina下這個值是2
ratio = window.devicePixelRatio || 1,
// 縮略圖大小
thumbnailWidth = 110 * ratio,
thumbnailHeight = 110 * ratio,
// 可能有pedding, ready, uploading, confirm, done.
state = 'pedding',
// 所有文件的進度信息,key為file id
percentages = {},
supportTransition = (function(){
var s = document.createElement('p').style,
r = 'transition' in s ||
'WebkitTransition' in s ||
'MozTransition' in s ||
'msTransition' in s ||
'OTransition' in s;
s = null;
return r;
})(),
// WebUploader實例
uploader;
if ( !WebUploader.Uploader.support() ) {
Feng.alert( 'Web Uploader 不支持您的瀏覽器!如果你使用的是IE瀏覽器,請嘗試升級 flash 播放器');
throw new Error( 'WebUploader does not support the browser you are using.' );
}
// 實例化
uploader = WebUploader.create({
pick: {
id: '#filePicker',
label: '點擊選擇圖片',
multiple:false,
name:'file'
},
dnd: '#uploader .queueList',
paste: document.body,
fileVal:'file',
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
},
// swf文件路徑
swf: Feng.ctxPath + '/static/js/plugins/webuploader/Uploader.swf',
disableGlobalDnd: false,
chunked: true,
server: Feng.ctxPath + '/product/uploadProductImage',
fileNumLimit: 1,
fileSizeLimit: 5 * 1024 * 1024, // 200 M
fileSingleSizeLimit: 1 * 1024 * 1024 // 50 M
});
// 添加“添加文件”的按鈕,
uploader.addButton({
id: '#filePicker2',
label: '繼續添加'
});
$(".imgShow").on( 'mouseenter', function() {
$(".file-panels").stop().animate({height: 30});
});
$(".imgShow").on( 'mouseleave', function() {
$(".file-panels").stop().animate({height: 0});
});
// 當有文件添加進來時執行,負責view的創建
function addFile( file ) {
var $li = $( '<li id="' + file.id + '">' +
'<p class="title">' + file.name + '</p>' +
'<p class="imgWrap"></p>'+
'<p class="progress"><span></span></p>' +
'</li>' ),
$btns = $('<div class="file-panel">' +
'<span class="cancel">刪除</span>' +
'<span class="rotateRight">向右旋轉</span>' +
'<span class="rotateLeft">向左旋轉</span></div>').appendTo( $li ),
$prgress = $li.find('p.progress span'),
$wrap = $li.find( 'p.imgWrap' ),
$info = $('<p class="error"></p>'),
showError = function( code ) {
switch( code ) {
case 'exceed_size':
text = '文件大小超出';
break;
case 'interrupt':
text = '上傳暫停';
break;
default:
text = '上傳失敗,請重試';
break;
}
$info.text( text ).appendTo( $li );
};
if ( file.getStatus() === 'invalid' ) {
showError( file.statusText );
} else {
// @todo lazyload
$wrap.text( '預覽中' );
uploader.makeThumb( file, function( error, src ) {
if ( error ) {
$wrap.text( '不能預覽' );
return;
}
var img = $('<img src="'+src+'">');
$wrap.empty().append( img );
}, thumbnailWidth, thumbnailHeight );
percentages[ file.id ] = [ file.size, 0 ];
file.rotation = 0;
}
file.on('statuschange', function( cur, prev ) {
if ( prev === 'progress' ) {
$prgress.hide().width(0);
} else if ( prev === 'queued' ) {
$li.off( 'mouseenter mouseleave' );
$btns.remove();
}
// 成功
if ( cur === 'error' || cur === 'invalid' ) {
console.log( file.statusText );
showError( file.statusText );
percentages[ file.id ][ 1 ] = 1;
} else if ( cur === 'interrupt' ) {
showError( 'interrupt' );
} else if ( cur === 'queued' ) {
percentages[ file.id ][ 1 ] = 0;
} else if ( cur === 'progress' ) {
$info.remove();
$prgress.css('display', 'block');
} else if ( cur === 'complete' ) {
$li.append( '<span class="success"></span>' );
}
$li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
});
$li.on( 'mouseenter', function() {
$btns.stop().animate({height: 30});
});
$li.on( 'mouseleave', function() {
$btns.stop().animate({height: 0});
});
$btns.on( 'click', 'span', function() {
var index = $(this).index(),
deg;
switch ( index ) {
case 0:
uploader.removeFile( file );
return;
case 1:
file.rotation += 90;
break;
case 2:
file.rotation -= 90;
break;
}
if ( supportTransition ) {
deg = 'rotate(' + file.rotation + 'deg)';
$wrap.css({
'-webkit-transform': deg,
'-mos-transform': deg,
'-o-transform': deg,
'transform': deg
});
} else {
$wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
});
$li.appendTo( $queue );
}
// 負責view的銷毀
function removeFile( file ) {
var $li = $('#'+file.id);
delete percentages[ file.id ];
updateTotalProgress();
$li.off().find('.file-panel').off().end().remove();
}
function updateTotalProgress() {
var loaded = 0,
total = 0,
spans = $progress.children(),
percent;
$.each( percentages, function( k, v ) {
total += v[ 0 ];
loaded += v[ 0 ] * v[ 1 ];
} );
percent = total ? loaded / total : 0;
spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
updateStatus();
}
function updateStatus() {
var text = '', stats;
if ( state === 'ready' ) {
text = '選中' + fileCount + '張圖片,共' +
WebUploader.formatSize( fileSize ) + '。';
} else if ( state === 'confirm' ) {
stats = uploader.getStats();
if ( stats.uploadFailNum ) {
text = '已成功上傳' + stats.successNum+ '張照片至XX相冊,'+
stats.uploadFailNum + '張照片上傳失敗,<a class="retry" href="#">重新上傳</a>失敗圖片或<a class="ignore" href="#">忽略</a>'
}
} else {
stats = uploader.getStats();
text = '共' + fileCount + '張(' +
WebUploader.formatSize( fileSize ) +
'),已上傳' + stats.successNum + '張';
if ( stats.uploadFailNum ) {
text += ',失敗' + stats.uploadFailNum + '張';
}
}
$info.html( text );
}
function setState( val ) {
var file, stats;
if ( val === state ) {
return;
}
$upload.removeClass( 'state-' + state );
$upload.addClass( 'state-' + val );
state = val;
switch ( state ) {
case 'pedding':
$placeHolder.removeClass( 'element-invisible' );
$queue.parent().removeClass('filled');
$queue.hide();
$statusBar.addClass( 'element-invisible' );
uploader.refresh();
break;
case 'ready':
$placeHolder.addClass( 'element-invisible' );
$( '#filePicker2' ).removeClass( 'element-invisible');
$queue.parent().addClass('filled');
$queue.show();
$statusBar.removeClass('element-invisible');
uploader.refresh();
break;
case 'uploading':
$( '#filePicker2' ).addClass( 'element-invisible' );
$progress.show();
$upload.text( '暫停上傳' );
break;
case 'paused':
$progress.show();
$upload.text( '繼續上傳' );
break;
case 'confirm':
$progress.hide();
$upload.text( '開始上傳' ).addClass( 'disabled' );
stats = uploader.getStats();
if ( stats.successNum && !stats.uploadFailNum ) {
setState( 'finish' );
return;
}
break;
case 'finish':
stats = uploader.getStats();
if ( stats.successNum ) {
Feng.alert( '上傳成功' );
parent.layer.close(window.parent.Product.layerIndex);
} else {
// 沒有成功的圖片,重設
state = 'done';
location.reload();
}
break;
}
updateStatus();
}
uploader.onUploadProgress = function( file, percentage ) {
var $li = $('#'+file.id),
$percent = $li.find('.progress span');
$percent.css( 'width', percentage * 100 + '%' );
percentages[ file.id ][ 1 ] = percentage;
updateTotalProgress();
};
uploader.onFileQueued = function( file ) {
fileCount++;
fileSize += file.size;
if ( fileCount === 1 ) {
$placeHolder.addClass( 'element-invisible' );
$statusBar.show();
}
addFile( file );
setState( 'ready' );
updateTotalProgress();
};
uploader.onFileDequeued = function( file ) {
fileCount--;
fileSize -= file.size;
if ( !fileCount ) {
setState( 'pedding' );
}
removeFile( file );
updateTotalProgress();
};
//上傳前傳參數到服務端
uploader.on('uploadBeforeSend', function (obj, data, headers) {
data.productId = productKey.defaultValue;
data.file = obj.file
});
uploader.on('uploadSuccess', function (file, response) {
$('.filelist').append('<input name="package[]" type="hidden" value="' + response._raw + '">')
});
uploader.on( 'all', function( type ) {
var stats;
switch( type ) {
case 'uploadFinished':
setState( 'confirm' );
break;
case 'startUpload':
setState( 'uploading' );
break;
case 'stopUpload':
setState( 'paused' );
break;
}
});
//錯誤提示
uploader.onError = function( code ) {
if(code == "F_DUPLICATE"){
Feng.alert("系統提示:請不要重復選擇文件!");
}else if(code == "Q_EXCEED_SIZE_LIMIT"){
Feng.alert("系統提示:<span class='C6'>所選附件總大小</span>不可超過<span class='C6'>" + allMaxSize + "M</span>哦!<br>換個小點的文件吧!");
}else{
Feng.alert( 'Eroor: ' + code );
}
};
$upload.on('click', function() {
if ( $(this).hasClass( 'disabled' ) ) {
return false;
}
if ( state === 'ready' ) {
uploader.upload();
} else if ( state === 'paused' ) {
uploader.upload();
} else if ( state === 'uploading' ) {
uploader.stop();
}
});
$info.on( 'click', '.retry', function() {
uploader.retry();
} );
$info.on( 'click', '.ignore', function() {
} );
$upload.addClass( 'state-' + state );
updateTotalProgress();
//刪除圖片
$(".btn-cancel").click(function () {
var operation = function () {
$.ajax({
type: "post",
url: Feng.ctxPath + '/product/deleteProductImage/' + $("#productKey").val(),
dataType: "json",
success: function (res) {
console.log(res);
$(".imgShow img").hide();
Feng.alert("刪除成功",3000);
parent.layer.close(window.parent.Product.layerIndex);
},
error: function (res) {
}
})
}
Feng.confirm("是否刪除該產品的圖片?", operation);
})
});
以上便是我所遇到的兩個問題,一個是回顯服務端圖片,一個就是ajax提交前傳參和服務端。
特殊說明:因為頁面用到的guns后台管理所以好多浮層插件都是guns封裝好的我直接用的,遇到不太明白的可以直接問哦!但願有所幫助~
