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