很简单的一款PHP+Ajax+plupload无刷新上传头像代码,兼容性很好,可以直接拿来用。你可以自定义各种类型的文件。本实例中只能上传"jpg", "png", "gif", "jpeg"等图片文件
引入jQuery库和plupload上传组件
1 <script type="text/javascript" src="jquery.js"></script> 2 <script type="text/javascript" src="plupload/plupload.full.min.js"></script>
plupload单图片上传配置
1 var uploader_avatar = new plupload.Uploader({//创建实例的构造方法 2 runtimes: 'gears,html5,html4,silverlight,flash', //上传插件初始化选用那种方式的优先级顺序 3 browse_button: ['avatar_uplpad_btn'], // 上传按钮 4 url: "ajax.php", //远程上传地址 5 flash_swf_url: 'js/plugins/plupload/Moxie.swf', //flash文件地址 6 silverlight_xap_url: 'js/plugins/plupload/Moxie.xap', //silverlight文件地址 7 filters: { 8 max_file_size: '10mb', //最大上传文件大小(格式100b, 10kb, 10mb, 1gb) 9 mime_types: [//允许文件上传类型 10 {title: "files", extensions: "jpg,png,gif,jpeg"} 11 ] 12 }, 13 multi_selection: false, //true:ctrl多文件上传, false 单文件上传 14 init: { 15 FilesAdded: function(up, files) { //文件上传前 16 17 uploader_avatar.start(); 18 }, 19 UploadProgress: function(up, file) { //上传中,显示进度条 20 var percent = file.percent; 21 $("#" + file.id).find('.bar').css({"width": percent + "%"}); 22 $("#" + file.id).find(".percent").text(percent + "%"); 23 }, 24 FileUploaded: function(up, file, info) { //文件上传成功的时候触发 25 var data = eval("(" + info.response + ")");//解析返回的json数据 26 $("#avatar_pic").html("<img src='" + data.pic + "'/>") 27 }, 28 Error: function(up, err) { //上传出错的时候触发 29 alert(err.message); 30 } 31 } 32 }); 33 uploader_avatar.init();