图片压缩 图片上传

  1<input class="form_upload_input" type="file" name="upload_input" accept="image/jpeg,image/png" title="上传图片"/>
  

  function getObjectURL(file){ 2 var url = url; 3 if(window.createObjectURL != undefined){ 4 url = window.createObjectURL(file); 5 }else if(window.URL != undefined){ 6 url = window.URL.createObjectURL(file); 7 }else if(window.webkitURL != undefined){ 8 url = window.webkitURL.createObjectURL(file); 9 } 10 return url; 11 } 12 //获取图片的src方法 13 14 var inputFile = $('.form_upload_input'); 15 16 inputFile.on('change',function(){ 17 18 var that = this.files, 19 i=0, 20 self=$(this), 21 filesLen=that.length; 22 23 $('.imgupload_progress[for='+self.attr('for')+']').show(); 24 self.parent('span').hide; 25 for(i=0; i<filesLen; i++){ 27 (function(i){ 29 var newImg = new Image(); 30 var w = 0,n=0,h=0; 31 newImg.src = getObjectURL(that[i]);//获取此次上传图片的地址 32 var M = that[i].size;//获取图片的大小 33 M = M/1024; 34 M = M/1024;//换算成M为单位的图片 36 newImg.onload = function(){ 37 w = newImg.naturalWidth;//获取上传图片的宽度 38 h = newImg.naturalHeight;//获取上传图片的高度 39 if( M > 2){//图片的大小大于2M就让他的宽度*0.8,用来限制图片压缩时图片的做大宽度 40 w *= 0.8; 41 } 43 if(M <= 2){ //图片小于2M不做压缩处理 44 var f = new FormData();//创建 formdate 对象,利用 FormData 对象,我们可以通过 JavaScript 用一些键值对来模拟一系列表单控件,
                            //我们还可以使用 XMLHttpRequest 的 send() 方法来异步的提交表单。与普通的 Ajax 相比,使用 FormData 的最大优点就是我们可以异步上传二进制文件。
45 f.append('upload_img',that[i]);// that[i]中已经包含了用户所选择的文件 50 var xhr = new XMLHttpRequest(); 51 xhr.open('POST', 'url'); 52 xhr.onload = function () { 53 if (xhr.status === 200) { 54 // self.attr('value', ''); 55 var data = $.parseJSON(xhr.responseText); 80 } 81 }; 82 xhr.onerror = function () { 83 $('.imgupload_progress[for='+self.attr('for')+']').hide(); 84 self.parent('span').show(); 85 $.messager.alert('提示', '图片上传失败', 'info'); 86 }; 87 xhr.upload.onprogress = function (e) { 88 // 上传进度 89 var percentComplete = ((e.loaded / e.total) || 0) * 100; 90 }; 91 xhr.send(f); 92 93 }else{//图片压缩处理 94 n = 0.7; 95 lrz(that[i], {width:w,fieldName: 'upload_img',quality: n}).then(function(rst){ 96 var xhr = new XMLHttpRequest(); 97 xhr.open('POST', 'url'); 98 xhr.onload = function () { 99 if (xhr.status === 200) { 100 126 } 127 }; 128 xhr.onerror = function () { 129 $('.imgupload_progress[for='+self.attr('for')+']').hide(); 130 self.parent('span').show(); 131 $.messager.alert('提示', '图片上传失败', 'info'); 132 }; 133 xhr.upload.onprogress = function (e) { 134 // 上传进度 135 var percentComplete = ((e.loaded / e.total) || 0) * 100; 136 }; 137 138 // 添加参数 139 rst.formData.append('fileLen', rst.fileLen); 140 141 // 触发上传 142 xhr.send(rst.formData); 143 144 /* ==================================================== */ 145 return rst; 146 }); 147 } 148 console.log(w,h,i); //输出图片的宽度、高度、循环图片该图片下标 153 } 155 })(i); 158 } 159 });

 ps:需要引入<script src="/js/lrz.all.bundle.js"></script>

posted @ 2016-07-07 10:23  蛋Mrs炒饭  阅读(241)  评论(0编辑  收藏  举报