webuploader上传控件是百度官方提供的一套基于html5的上传解决方案.本文主要讲解webuploader配合fastDFS做跨域远程上传的实现方法,有不对之处还请大家提意见,可以直接到久久博客www.99xq.cn留言.
var upload_url = 'https://www.99xq.cn/';
var success_callback = function(data){
upload_ok(data);
};
回调函数名字upload_ok(),在upload.js文件中对这个函数进行了调用.
具体upload.js代码如下:
// 图片上传demo by 久久博客https://www.99xq.cn/
jQuery.support.cors = true
jQuery(function() {
var $ = jQuery,
$list = $('#fileList'),
// 优化retina, 在retina下这个值是2
ratio = window.devicePixelRatio || 1,
// 缩略图大小
thumbnailWidth = 100 * ratio,
thumbnailHeight = 100 * ratio,
// Web Uploader实例
uploader;
// 初始化Web Uploader
uploader = WebUploader.create({
// 自动上传。
auto: true,
method: 'POST',
sendAsBinary: true,
// swf文件路径
swf: 'Uploader.swf',
// 文件接收服务端。
server: upload_url ? upload_url : 'http://www.99xq.cn/',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#filePicker',
// 只允许选择文件,可选。
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});
// 当有文件添加进来的时候
uploader.on( 'fileQueued', function( file ) {
var $li = $(
'
'' +
'
'
),
$img = $li.find('img');
$list.append( $li );
// 创建缩略图
uploader.makeThumb( file, function( error, src ) {
if ( error ) {
$img.replaceWith('不能预览');
return;
}
$img.attr( 'src', src );
}, thumbnailWidth, thumbnailHeight );
});
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
var $li = $( '#'+file.id ),
$percent = $li.find('.progress span');
// 避免重复创建
if ( !$percent.length ) {
$percent = $('
.appendTo( $li )
.find('span');
}
$percent.css( 'width', percentage * 100 + '%' );
});
// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on( 'uploadSuccess', function( file,data ) {
var arr = data['data'];
var name = arr['name'];
var size = arr['size'];
var type = arr['type'];
var path = arr['url'];
var deviceid = $("#de_id").html();
if(typeof(success_callback) == 'function'){
success_callback(arr);
}else{
$.post('http://www.99xq.cn/',{name:name,size:size,type:type,path:path},function(html){
var arr = $.parseJSON(html);
if(arr.error=='0') $( '#'+file.id ).addClass('upload-state-done');
});
}
});
// 文件上传失败,现实上传出错。
uploader.on( 'uploadError', function( file ) {
var $li = $( '#'+file.id ),
$error = $li.find('div.error');
// 避免重复创建
if ( !$error.length ) {
$error = $('
}
$error.text('上传失败');
});
// 完成上传完了,成功或者失败,先删除进度条。
uploader.on( 'uploadComplete', function( file,data ) {
$( '#'+file.id ).find('.progress').remove();
});
});
回调函数upload_ok()代码如下:主要是对数据进行后续处理.
/**
* 上传成功后的回调 by 久久博客www.99xq.cn 转载请注明出处
* file格式如下:
url:/group1/M00/00/03/wKhnF1YfjraAcCg2AAAS-S0upY4479.jpg
op:upload
buff_file_type:image
dir:yunyichong
buff_type:jpg
id:WU_FILE_0
name:1003140183.png
type:image/png
lastModifiedDate:Thu Aug 22 2013 17:56:32 GMT+0800 (中国标准时间)
size:5213
*/
function upload_ok(file) {
$.post( 'https://www.99xq.cn/', file, function(data){
$('#WU_FILE_X').remove();
if(data.status == 'ok'){
showmsg('头像上传成功', 2);
}
else{
showmsg('头像上传失败', 3);
}
},'json' );
}