最近在写一个照片上传的功能,要求使用WebUploader这个插件官网Demo地址如下:
http://fex.baidu.com/webuploader/demo.html?qq-pf-to=pcqq.discussion
但是从我这里使用Demo一直照片上传错误,不知道什么原因,后来就 下载实例代码自己写了一个简单 的上传。
先要准备好四个文件:
1.webuploader.js
2.webuploader.css
3.Uploader.swf
4.jquery.js
文件导入后,在页面中初始化webUploader,设置必要的属性,是否自动上传、swf文件路径、server服务端地址、上传属性的Name、提交方式、文件类型、表单参数,以及后面的操作事件详细见代码。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/webuploader.css">
<script type="text/javascript" src="../js/jquery-2.2.2.js"></script>
<script type="text/javascript" src="../js/webuploader.js"></script>
<script type="text/javascript">
//图片上传demo
$(function() {
var $ = jQuery,
$list = $('#fileList'),
// 优化retina, 在retina下这个值是2
ratio = window.devicePixelRatio || 1,
// 缩略图大小
thumbnailWidth = 100 * ratio,
thumbnailHeight = 100 * ratio,
//可能有pedding, ready, uploading, confirm, done.
state = 'pedding',
// 添加的文件数量
fileCount = 0,
// 添加的文件总大小
fileSize = 0,
// 所有文件的进度信息,key为file id
percentages = {},
// Web Uploader实例
uploader;
// 初始化Web Uploader
uploader = WebUploader.create({
// 自动上传。
auto: true,
// swf文件路径
swf:'../js/Uploader.swf',
// 文件接收服务端。
server: '../rest/realNameAuth/doUploadFile',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#filePicker',
//上传属性Name
fileVal: 'file',
//提交方式
method:'post',
// 只允许选择文件,可选。
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png'
},
formData:{
phone:18551804986
}
});
// 当有文件添加进来的时候
uploader.on( 'fileQueued', function( 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;
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.ratation = 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' ) {
showError( file.statusText );
percentages[ file.id ][ 1 ] = 1;
} else if ( cur === 'queued' ) {
percentages[ file.id ][ 1 ] = 0;
} else if ( cur === 'progress' ) {
$info.remove();
$prgress.css('display', 'block');
}
$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.ratation += 90;
break;
case 2:
file.ratation -= 90;
break;
}
// -webkit-transform: rotate(90deg);
index && (deg = 'rotate(' + file.ratation + 'deg)', $wrap.css({
'-webkit-transform': deg,
'-mos-transform': deg,
'-o-transform': deg,
'transform': deg
}));
});
$list.append( $li );
});
uploader.on( 'all', function( type ) {
var stats;
switch( type ) {
case 'uploadFinished':
setState( 'confirm' );
break;
case 'startUpload':
setState( 'uploading' );
break;
case 'stopUpload':
setState( 'paused' );
break;
}
});
function setState( val ) {
var file, stats;
if ( val === state ) {
return;
}
state = val;
switch ( state ) {
case 'pedding':
$placeHolder.show();
$queue.hide();
$statusBar.hide();
break;
case 'ready':
$placeHolder.hide();
$( '#filePicker2' ).show();
$queue.show();
$statusBar.show();
break;
case 'uploading':
$( '#filePicker2' ).hide();
break;
case 'paused':
break;
case 'confirm':
stats = uploader.getStats();
if ( stats.successNum && !stats.uploadFailNum ) {
setState( 'finish' );
return;
}
break;
case 'finish':
stats = uploader.getStats();
if ( stats.successNum ) {
alert( '上传成功' );
} else {
// 没有成功的图片,重设
state = 'done';
location.reload();
}
break;
}
}
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
var $li = $( '#'+file.id ),
$percent = $li.find('.progress span');
// 避免重复创建
if ( !$percent.length ) {
$percent = $('<p class="progress"><span></span></p>')
.appendTo( $li )
.find('span');
}
$percent.css( 'width', percentage * 100 + '%' );
});
// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on( 'uploadSuccess', function( file ) {
$( '#'+file.id ).addClass('upload-state-done');
});
// 文件上传失败,现实上传出错。
uploader.on( 'uploadError', function( file ) {
var $li = $( '#'+file.id ),
$error = $li.find('div.error');
// 避免重复创建
if ( !$error.length ) {
$error = $('<div class="error"></div>').appendTo( $li );
}
$error.text('上传失败');
});
// 完成上传完了,成功或者失败,先删除进度条。
uploader.on( 'uploadComplete', function( file ) {
$( '#'+file.id ).find('.progress').remove();
});
});
</script>
</head>
<body>
<!--dom结构部分-->
<div id="uploader-demo">
<!--用来存放item-->
<div id="fileList" class="uploader-list"></div>
<div id="filePicker">选择图片</div>
</div>
</body>
</html>