做微信网页版图片上传的时候遇到了一个问题,微信截图可以上传,保存下来或是拍照的图片不能上传,最后发现是图片格式的问题
以往图片上传都是‘jpeg、jpg、png、gif’这样的格式都能上传,但是微信网页内图片上传时,其它格式都能上传,只有jpeg后缀的图片不能上传,晕死
解决办法:判定后缀是否为jpeg,如果是,重新建一个上传文件对象,传入名字,格式就可以了
如:
var afile;
const file = $("#fileimg").get(0).files[0];if(file.type.indexOf('jpeg') != -1){
afile = new File([file], new Date().getTime()+".jpg", {type: 'image/jpg'}); }else{ afile = file; }
图片上传压缩图片大小
1 // 压缩版 2 function uploadImg(formId, filename, showimg){ 3 var file; 4 var inputImgUrl = $("#img").val(); 5 var afile = $("#fileimg").get(0).files[0]; 6 7 if(['jpeg', 'png', 'gif', 'jpg'].indexOf(afile.type.split("/")[1])<0){ 8 toastr.error("请上传图片格式文件") 9 return; 10 } 11 12 if(afile.type.indexOf('jpeg') != -1){ 13 file = new File([afile], new Date().getTime()+".jpg", {type: 'image/jpg'}); 14 }else{ 15 file = afile; 16 } 17 18 var formData = new FormData(); 19 20 if(file.size/1024 > 1025) { //大于1M,进行压缩上传 21 photoCompress(file, 640, function(base64Codes){ 22 var blob = convertBase64UrlToBlob(base64Codes); 23 formData.append("file", blob, file.name); 24 console.log("将blob对象转成formData对象:" + file.name); 25 UploadImgAjax(formData,inputImgUrl,showimg); 26 }); 27 }else{ 28 formData.append("file", file); 29 UploadImgAjax(formData,inputImgUrl,showimg); 30 } 31 } 32 33 /* 34 三个参数 35 file:一个是文件(类型是图片格式), 36 w:一个是文件压缩的后宽度,宽度越小,字节越小 37 objDiv:一个是容器或者回调函数 38 photoCompress() 39 */ 40 function photoCompress(file,w,objDiv){ 41 var ready=new FileReader(); 42 /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/ 43 ready.readAsDataURL(file); 44 ready.οnlοad=function(){ 45 var re=this.result; 46 canvasDataURL(re,w,objDiv) 47 } 48 } 49 function canvasDataURL(path, w, callback){ 50 var newImage = new Image(); 51 var quality = 0.6; //压缩系数0-1之间 52 newImage.src = path; 53 newImage.setAttribute("crossOrigin", 'Anonymous'); //url为外域时需要 54 var imgWidth, imgHeight; 55 56 newImage .onload = function(){ 57 imgWidth = this.width; 58 imgHeight = this.height; 59 //生成canvas 60 var canvas = document.createElement("canvas"); 61 var ctx = canvas.getContext("2d"); 62 if (imgWidth > w) { 63 canvas.width = w; 64 canvas.height = w * imgHeight / imgWidth; 65 }else { 66 canvas.width = imgWidth; 67 canvas.height = imgHeight; 68 quality = 0.6; 69 } 70 ctx.clearRect(0, 0, canvas.width, canvas.height); 71 ctx.fillStyle = "#fff"; 72 ctx.fillRect(0, 0, canvas.width, canvas.height); 73 ctx.drawImage(this, 0, 0, canvas.width, canvas.height); 74 var base64 = canvas.toDataURL("image/jpeg", quality);//压缩语句 75 76 //回调函数返回base64的值 77 callback(base64); 78 } 79 } 80 81 /** 82 * 将以base64的图片url数据转换为Blob 83 * @param urlData 84 * 用url方式表示的base64图片数据 85 */ 86 function convertBase64UrlToBlob(urlData){ 87 var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1], 88 bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); 89 while(n--){ 90 u8arr[n] = bstr.charCodeAt(n); 91 } 92 return new Blob([u8arr], {type:mime}); 93 } 94 95 function UploadImgAjax(formData,inputImgUrl,showimg){ 96 $.ajax({ 97 url: 上传图片接口, 98 type: 'POST', 99 data: formData, // 上传formdata封装的数据100 dataType: 'JSON',101 cache: false, // 不缓存102 processData: false, // jQuery不要去处理发送的数据103 contentType: false, // jQuery不要去设置Content-Type请求头104 success:function (ret) { //成功回调105 var img = ret.pic;106 if(inputImgUrl){107 inputImgUrl += "," + ret.pic;108 }else{109 inputImgUrl = ret.pic;110 }111 $('.'+showimg).before("");112 $('#img').val(inputImgUrl);113 },114 error: function(){115 console.log("error");116 toastr.error(ret.message);117 }118 });119 }
后续增加删除上传过的图片
$(".attach-mypic").on("click", ".omit", function(){ var imgVal=$("#img").val(),thisImgUrl = $(this).siblings("img")[0].src,tempUrlArr=imgVal.split(","); for(var i=0;i
在网上找了个兼容版本的,但是在ios上图片没有压缩,先把代码放上,有时间再测试(此版代码压缩没有效果,如需要压缩图片,用上面的版本)
1 const imgFile = {}; 2 var inputImgUrl = $("#img").val(); 3 function uploadImg(formId, filename, showimg){ 4 var afile; 5 const file = $("#fileimg").get(0).files[0]; 6 const imgMasSize = 1024 7 8 if(['jpeg', 'png', 'gif', 'jpg'].indexOf(file.type.split("/")[1])<0){ 9 toastr.error("请上传图片格式文件") 10 return; 11 } 12 13 if(file.type.indexOf('jpeg') != -1){ 14 afile = new File([file], new Date().getTime()+".jpg", {type: 'image/jpg'}); 15 }else{ 16 afile = file; 17 } 18 19 // if(file.size/1024 > 1025){ 20 // alert("太大了"); 21 // } 22 23 if(!!window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){ 24 transformFileToFormData(afile); 25 return; 26 } 27 28 transformFileToDataUrl(afile); 29 30 } 31 32 function transformFileToFormData(file){ 33 const formData = new FormData(); 34 35 formData.append('type', file.type || "image/jpg"); 36 37 formData.append('size', file.size); 38 39 formData.append('name', file.name); 40 41 formData.append('lastModifiedDate', file.lastModifiedDate); 42 43 formData.append('file', file); 44 45 // uploadImg(formData); 46 UploadImgAjax(formData); 47 } 48 49 function transformFileToDataUrl(file){ 50 const imgCompassMaxSize = 1024; 51 52 imgFile.type = file.type || 'image/jpg'; 53 imgFile.size = file.size; 54 imgFile.name = file.name; 55 imgFile.lastModifiedDate = file.lastModifiedDate; 56 57 const reader = new FileReader(); 58 59 reader.onload = function(e){ 60 const result = e.target.result; 61 62 if(result.length < imgCompassMaxSize){ 63 compress(result, processData, false); 64 }else{ 65 compress(result, processData); 66 } 67 }; 68 69 reader.readAsDataURL(file); 70 } 71 72 // 使用canvas绘制图片并压缩 73 function compress (dataURL, callback, shouldCompress = true) { 74 const img = new window.Image(); 75 76 img.src = dataURL; 77 78 img.onload = function () { 79 const canvas = document.createElement('canvas'); 80 const ctx = canvas.getContext('2d'); 81 82 canvas.width = img.width; 83 canvas.height = img.height; 84 85 ctx.drawImage(img, 0, 0, canvas.width, canvas.height); 86 87 let compressedDataUrl; 88 89 if(shouldCompress){ 90 compressedDataUrl = canvas.toDataURL(imgFile.type, 0.2); 91 } else { 92 compressedDataUrl = canvas.toDataURL(imgFile.type, 1); 93 } 94 95 callback(compressedDataUrl); 96 } 97 } 98 99 function processData (dataURL) {100 // 这里使用二进制方式处理dataURL101 const binaryString = window.atob(dataURL.split(',')[1]);102 const arrayBuffer = new ArrayBuffer(binaryString.length);103 const intArray = new Uint8Array(arrayBuffer);104 const imgFile = this.imgFile;105 106 for (let i = 0, j = binaryString.length; i < j; i++) {107 intArray[i] = binaryString.charCodeAt(i);108 }109 110 const data = [intArray];111 112 let blob;113 114 try {115 blob = new Blob(data, { type: imgFile.type });116 } catch (error) {117 window.BlobBuilder = window.BlobBuilder ||118 window.WebKitBlobBuilder ||119 window.MozBlobBuilder ||120 window.MSBlobBuilder;121 if (error.name === 'TypeError' && window.BlobBuilder){122 const builder = new BlobBuilder();123 builder.append(arrayBuffer);124 blob = builder.getBlob(imgFile.type);125 } else {126 // Toast.error("版本过低,不支持上传图片", 2000, undefined, false);127 throw new Error('版本过低,不支持上传图片');128 }129 }130 131 // blob 转file132 const fileOfBlob = new File([blob], imgFile.name, {type: "image/jpg"});133 const formData = new FormData();134 135 // type136 formData.append('type', imgFile.type);137 // size138 formData.append('size', fileOfBlob.size);139 // name140 formData.append('name', imgFile.name);141 // lastModifiedDate142 formData.append('lastModifiedDate', imgFile.lastModifiedDate);143 // append 文件144 formData.append('file', fileOfBlob);145 console.log(formData);146 147 // uploadImg(formData);148 UploadImgAjax(formData);149 }150 151 function UploadImgAjax(formData){152 $.ajax({153 url: '/community/upload',154 type: 'POST',155 data: formData, // 上传formdata封装的数据156 dataType: 'JSON',157 cache: false, // 不缓存158 processData: false, // jQuery不要去处理发送的数据159 contentType: false, // jQuery不要去设置Content-Type请求头160 success:function (ret) { //成功回调161 var img = ret.pic;162 if(inputImgUrl){163 inputImgUrl += "," + ret.pic;164 }else{165 inputImgUrl = ret.pic;166 }167 $('.add').before("");168 $('#img').val(inputImgUrl);169 },170 error: function(){171 console.log("error");172 toastr.error(ret.message);173 }174 });175 }