一行代码实现头像上传,图片大小、尺寸,类型验证
html调用
<img src="这里放默认头像" id="preview" onclick="uploader.fileInput.click()"/>
js调用
var uploader = new ImageUploader({accept: ['jpg', 'png', 'gif'],maxSize: 1,maxWidth: 800,maxHeight: 1000,uploadUrl: 'upload',success: function(url) {//上传成功回调}});
调用效果如图
直接点击头像即可实现图片上传
以下是插件代码
function ImageUploader(options) {this.options = options || {}; // 参数配置this.fileInput = null; // 文件输入框this.previewImage = null; // 预览图片this.uploadUrl = options.uploadUrl || '/upload'; // 上传接口地址(默认值为'/upload')// 初始化this.init();}
// 初始化方法ImageUploader.prototype.init = function() {var that = this;// 创建文件输入框this.createFileInput();// 监听文件选择事件this.fileInput.addEventListener('change', function(event) {var file = event.target.files[0];// 判断图片类型if (that.options.accept && !that.checkFileType(file)) {alert('只能上传 ' + that.options.accept.join(',') + ' 类型的图片');return;}// 判断图片大小if (that.options.maxSize && file.size > that.options.maxSize * 1024 * 1024) {alert('图片大小不能超过 ' + that.options.maxSize + 'MB');return;}// 验证图片尺寸var reader = new FileReader();reader.onload = function() {var img = new Image();img.onload = function() {if (that.options.maxWidth && img.width > that.options.maxWidth) {alert('图片宽度不能超过 ' + that.options.maxWidth + '像素');return;}if (that.options.maxHeight && img.height > that.options.maxHeight) {alert('图片高度不能超过 ' + that.options.maxHeight + '像素');return;}that.uploadFile(file);};img.src = reader.result;};reader.readAsDataURL(file);});};
// 创建文件输入框ImageUploader.prototype.createFileInput = function() {var input = document.createElement('input');input.type = 'file';input.style.display = 'none';if (this.options.accept) {input.accept = this.options.accept.join(',');}document.body.appendChild(input);this.fileInput = input;};
// 检查文件类型是否符合要求ImageUploader.prototype.checkFileType = function(file) {var fileType = file.type;if (!fileType) {return false;}fileType = fileType.split('/').pop();return this.options.accept.indexOf(fileType) !== -1;};
// 执行上传操作ImageUploader.prototype.uploadFile = function(file) {var that = this;var xhr = new XMLHttpRequest();xhr.open('POST', this.uploadUrl, true);xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');var formData = new FormData();formData.append('file', file);xhr.onreadystatechange = function() {if (xhr.readyState === 4) {if (xhr.status === 200 || xhr.status === 201) {var responseText = JSON.parse(xhr.responseText);if (responseText.errno === 0) {that.showUploaded(responseText.data.url);} else {alert(responseText.msg);}} else {alert('上传失败,请稍后再试!');}}};xhr.send(formData);};