压缩部分是从网上搞下来的,上传部分是本身写的,至关于在其余人的基础上完善了这个压缩上传流程。javascript
压缩部分,压缩率通常,重在浏览器支持方面好些,使用了FileReader和Canvas实现,FileReader浏览器支持方面还不错:php
上传部分,使用XMLHttpRequest上传Blob实现,浏览器方面比FileReader差一点,不过也差不了多少,主要在安卓浏览器方面差一些:html
大概根据上图总结能支持到IE10及以上版本、大多数现代浏览器及多数安卓与ios浏览器。java
为了保持ie浏览器尽可能向下支持,因此用的方法不算太多,压缩比可能对比其余压缩插件不大。
开发时为了方便,插件须要jQuery支持,插件须要放在jQuery以后加载。jquery
使用方法:ios
若是上传时提示上传失败,检查上传地址是否正确而且控制台提示Access-Control-Allow-Origin啥啥的就是服务接收段须要容许跨域,例如php须要加上
header( "Access-Control-Allow-Origin:*" );
下面是源码
html页面:git
<!doctype html> <html> <head> <meta charset="utf-8"> <title>图片压缩上传</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script src="UploadPic.js"></script> </head> <body> <input id="files" type="file" accept="image/*;capture=camera" class="input"> </body> </html>
UploadPic.js:json
$("#files").ready(UploadPic_init);//框件初始加载与绑定 /** * 初始化UploadPic * @constructor */ function UploadPic_init() { UploadPic.prototype.url = '';//初始上传url var u = new UploadPic(); u.init({ input: document.querySelector("#files"),//框件绑定 callback: function (base64) { var _this=this; //获取图片类型 var typ = base64.match(/data:image\/([^\"]*)\;base64/); //base64 转 blob var ccBlob= _this._getBlobBydataURI(base64,'image/'+typ[1]); if(ccBlob.size>_this.fileSize){ ccBlob=_this.input.files[0]; } var formData = new FormData(); var filname="file_"+_this.fileName+"."+typ[1]; formData.append("files", ccBlob ,filname); //组建XMLHttpRequest 上传文件 var request = new XMLHttpRequest(); //上传链接地址 request.open("POST", _this.url); request.onreadystatechange=function() { if (request.readyState==4) { if(request.status==200){ console.log(request.response); _this.uploadResult(request.response); _this.emptyFile(); }else{ alert("上传失败,检查上传地址是否正确"); _this.emptyFile(); } } } request.send(formData); }, loading: function () { } }); } /** * UploadPic * 初始化配置 init * 自定义文件框架change动做 changeAction * 自定义上传结果动做 uploadResult */ function UploadPic() { this.isrun=0; this.sw = 0; this.sh = 0; this.tw = 0; this.th = 0; this.scale = 0; this.maxWidth = 0; this.maxHeight = 0; this.maxSize = 0; this.fileSize = 0; this.fileDate = null; this.fileType = ''; this.fileName = ''; this.input = null; this.canvas = null; this.mime = {}; this.type = ''; this.callback = function () {}; this.loading = function () {}; } /** * 初始化 */ UploadPic.prototype.init = function (options) { this.maxWidth = options.maxWidth || 1080;//图片最大宽度 this.maxHeight = options.maxHeight || 1024;//图片最大高度 this.maxSize = options.maxSize || 50 * 1024 * 1024;//图片限制大小 this.input = options.input; this.mime = {'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp'}; this.callback = options.callback || function () {}; this.loading = options.loading || function () {}; this.url = this.url? this.url : "http://127.0.0.1/upload.php"; this._addEvent();//绑定change事件 }; /** * @description 绑定事件 * @param {Object} elm 元素 * @param {Function} fn 绑定函数 */ UploadPic.prototype._addEvent = function () { var _this = this; function tmpSelectFile(ev) { var icontinue=_this.changeAction();//自定义change事件 if(!icontinue){return;} _this._handelSelectFile(ev.target.files[0]); } this.input.addEventListener('change', tmpSelectFile, false); }; /** * @description 加载图片 * @param {Object} ev 元素 * */ UploadPic.prototype._handelSelectFile = function (ev) { var file = ev; try{ this.type = file.type; }catch(e){ this.isrun=0; this.emptyFile(); return; } // 若是没有文件类型,则经过后缀名判断(解决微信及360浏览器没法获取图片类型问题) if (!this.type) { this.type = this.mime[file.name.match(/\.([^\.]+)$/i)[1]]; } if (!/image.(png|jpg|jpeg|bmp)/.test(this.type)) { alert('选择的文件类型不是图片'); return; } if (file.size > this.maxSize) { alert('选择文件大于' + this.maxSize / 1024 / 1024 + 'M,请从新选择'); return; } this.fileName = this._muuid(); this.fileSize = file.size; this.fileType = this.type; this.fileDate = file.lastModifiedDate; this._readImage(file); }; /** * @description 读取图片文件 * @param {Object} image 图片文件 */ UploadPic.prototype._readImage = function (file) { var _this = this; function tmpCreateImage(uri) { _this._createImage(uri); } this.loading(); this._getURI(file, tmpCreateImage); }; /** * @description 经过文件得到URI * @param {Object} file 文件 * @param {Function} callback 回调函数,返回文件对应URI * return {Bool} 返回false */ UploadPic.prototype._getURI = function (file, callback) { try{ var reader = new FileReader(); }catch(e){ alert('图片上传失败,请升级浏览器'); return; } var _this = this; function tmpLoad() { // 头不带图片格式,需填写格式 var re = /^data:base64,/; var ret = this.result + ''; if (re.test(ret)) ret = ret.replace(re, 'data:' + _this.mime[_this.fileType] + ';base64,'); callback && callback(ret); } reader.onload = tmpLoad; reader.readAsDataURL(file); return false; }; /** * @description 建立图片 * @param {Object} image 图片文件 */ UploadPic.prototype._createImage = function (uri) { var img = new Image(); var _this = this; function tmpLoad() { _this._drawImage(this); } img.onload = tmpLoad; img.src = uri; }; /** * @description 建立Canvas将图片画至其中,并得到压缩后的文件 * @param {Object} img 图片文件 * @param {Number} width 图片最大宽度 * @param {Number} height 图片最大高度 * @param {Function} callback 回调函数,参数为图片base64编码 * return {Object} 返回压缩后的图片 */ UploadPic.prototype._drawImage = function (img, callback) { this.sw = img.width; this.sh = img.height; this.tw = img.width; this.th = img.height; this.scale = (this.tw / this.th).toFixed(2); if (this.sw > this.maxWidth) { this.sw = this.maxWidth; this.sh = Math.round(this.sw / this.scale); } if (this.sh > this.maxHeight) { this.sh = this.maxHeight; this.sw = Math.round(this.sh * this.scale); } this.canvas = document.createElement('canvas'); var ctx = this.canvas.getContext('2d'); this.canvas.width = this.sw; this.canvas.height = this.sh; ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, this.sw, this.sh); this.callback(this.canvas.toDataURL(this.type)); ctx.clearRect(0, 0, this.tw, this.th); this.canvas.width = 0; this.canvas.height = 0; this.canvas = null; }; /** * 根据base64 内容 取得 bolb */ UploadPic.prototype._getBlobBydataURI = function (dataURI,type) { var binary = atob(dataURI.split(',')[1]); var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([new Uint8Array(array)], {type:type }); }; /** * 生成uuid */ UploadPic.prototype._muuid = function () { var s = []; var hexDigits = "0123456789abcdef"; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010 s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 s[8] = s[13] = s[18] = s[23] = "-"; var uuid = s.join(""); return uuid; }; /** * 清空file */ UploadPic.prototype.emptyFile = function () { var file = $("#"+this.input.id); file.after(file.clone().val("")); file.remove(); this.input=document.querySelector("#"+this.input.id); file.ready(this._addEvent()); }; /** * 自定义文件框件change动做 */ UploadPic.prototype.changeAction = function () { if(this.isrun==0){ this.isrun=1; }else{ alert("上传失败,有图片未上传完成"); //清空file this.emptyFile(); return false;//终止程序标识 } this.fileName=this._muuid(); return true;//继续程序标识 }; /** * 自定义上传结果 */ UploadPic.prototype.uploadResult = function (json) { this.isrun=0; alert("上传完成"); }