js文件上传 自定义压缩文件和文件格式及大小限制
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 $(function () { 2 var count = 0; 3 /*----------------------------------------------文件上传-----------------------------------------*/ 4 5 window.uploadFile = function (url, filetypes, callback) { 6 7 var txt = "文档文件限制20M,压缩文件限制100M,仅支持jpg png gif doc docx ppt pptx xls xlsx zip文件上传,图片和文件请分开上传!"; 8 var option = { 9 title: "系统提醒", 10 btn: parseInt("0011", 2), 11 onOk: function () { 12 var input = document.createElement("input"); 13 input.setAttribute("type", 'file'); 14 input.setAttribute("id", parseInt(Math.random() * 10000)); 15 input.setAttribute("accept", 'image/*,application/msword,'+ 16 'application/vnd.ms-powerpoint,application/vnd.ms-excel,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/x-zip-compressed'); 17 input.setAttribute("style", 'display:none'); 18 input.setAttribute("multiple", 'multiple'); 19 document.body.appendChild(input); 20 if (count > 1) input.setAttribute("multiple", 'multiple'); 21 input.onchange = function (event) { 22 $("body").mLoading("show"); 23 $(".mloading-text").text("文件上传中..."); 24 var fd = new FormData(); 25 var form = new FormData(); 26 var files = input.files; 27 verification(files, function (res) { 28 if (res.IsPass) { 29 if (!res.IsFile) { 30 url = window.FileuploadServer + "?SaveType=2"; 31 } 32 var bigfiles = ""; 33 var allPromises = []; 34 for (var i = 0; i < files.length; i++) { 35 console.log(files[i]); 36 let filesize = Math.round(files[i].size / 1024 * 100) / 100; 37 if (files[i].name.toLowerCase().indexOf("pdf") > -1 38 || files[i].name.toLowerCase().indexOf("ppt") > -1 39 || files[i].name.toLowerCase().indexOf("pptx") > -1 40 || files[i].name.toLowerCase().indexOf("word") > -1 41 || files[i].name.toLowerCase().indexOf("doc") > -1 42 || files[i].name.toLowerCase().indexOf("docx") > -1 43 || files[i].name.toLowerCase().indexOf("xls") > -1 44 || files[i].name.toLowerCase().indexOf("xlsx") > -1 45 || files[i].name.toLowerCase().indexOf("pdf") > -1 46 ) { 47 if (filesize > 30720) { 48 if (bigfiles == "") { 49 bigfiles = files[i].name; 50 } else { 51 bigfiles += "、" + files[i].name; 52 } 53 } else { 54 form.append('file' + i, files[i]); 55 } 56 } else if (files[i].name.toLowerCase().indexOf("zip")) 57 { 58 if (filesize > 102400) { 59 if (bigfiles == "") { 60 bigfiles = files[i].name; 61 } else { 62 bigfiles += "、" + files[i].name; 63 } 64 } else { 65 form.append('file' + i, files[i]); 66 } 67 } 68 else if (files[i].name.indexOf("jpeg") > -1 69 || files[i].name.toLowerCase().indexOf("png") > -1 70 || files[i].name.toLowerCase().indexOf("jpg") > -1 71 || files[i].name.toLowerCase().indexOf("gif") > -1 72 ) { 73 var filename = files[i].name.toLowerCase(); 74 var file = files[i]; 75 if (filesize > 2048) { 76 77 allPromises.push(photoCompress(file, { quality: 1 }).then(function (res) { 78 var data = new Object(); 79 data.filename = filename; 80 data.basecode = res; 81 return data; 82 })) 83 84 } else { 85 form.append('file' + i, files[i]); 86 } 87 88 } else { 89 $("body").mLoading("hide"); 90 toastr.error("上传文件格式不符合规范"); 91 files = []; 92 return false; 93 } 94 95 } 96 97 if (allPromises.length == 0) { 98 if (bigfiles != "") { 99 $("body").mLoading("hide"); 100 toastr.error("以下文件不符合规范:" + bigfiles + ";图片限制为2M、文件限制为20M、压缩文件限制为50M"); 101 } else { 102 103 $.ajax({ 104 data: form, 105 type: "POST", 106 processData: false, 107 contentType: false, 108 url: url, 109 success: function (res) { 110 console.log(res); 111 if (filetypes.indexOf(".jpg") != -1) { 112 113 } 114 res.Alias = []; 115 document.body.removeChild(input); 116 if (res.FileNames != undefined) { 117 if (res.FileNames.length == files.length) { 118 for (var i = 0; i < res.FileNames.length; i++) { 119 res.Alias[res.Alias.length] = files[i].name; 120 121 } 122 } 123 } else { 124 125 } 126 $("body").mLoading("hide"); 127 callback(res); 128 } 129 }); 130 } 131 } else { 132 Promise 133 .all(allPromises) 134 .then(function (results) { 135 for (var i = 0; i < results.length; i++) { 136 var bl = convertBase64UrlToBlob(results[i].basecode); 137 form.append("file", bl, results[i].filename); // 文件对象 138 } 139 $.ajax({ 140 data: form, 141 type: "POST", 142 processData: false, 143 contentType: false, 144 url: url, 145 success: function (res) { 146 console.log(res); 147 if (filetypes.indexOf(".jpg") != -1) { 148 149 } 150 res.Alias = []; 151 152 if (res.FileNames != undefined) { 153 if (res.FileNames.length == files.length) { 154 for (var i = 0; i < res.FileNames.length; i++) { 155 res.Alias[res.Alias.length] = files[i].name; 156 157 } 158 } 159 } else { 160 161 } 162 $("body").mLoading("hide"); 163 callback(res); 164 } 165 }); 166 }); 167 } 168 } else { 169 $("body").mLoading("hide"); 170 toastr.error("请把图片和文件分开上传!"); 171 } 172 }) 173 174 175 } 176 input.click(); 177 } 178 }; 179 window.wxc.xcConfirm(txt, "custom", option,"开始上传","关闭"); 180 181 182 } 183 //验证上传的文件是否为统一类型 184 function verification(files, callback) 185 { 186 var res = new Object(); 187 var FirstIsFile = false; 188 var OtherIsFile = false; 189 for (var i = 0; i < files.length; i++) { 190 if (files[i].name.indexOf("pdf") > -1 191 || files[i].name.toLowerCase().indexOf("ppt") > -1 192 || files[i].name.toLowerCase().indexOf("pptx") > -1 193 || files[i].name.toLowerCase().indexOf("word") > -1 194 || files[i].name.toLowerCase().indexOf("doc") > -1 195 || files[i].name.toLowerCase().indexOf("docx") > -1 196 || files[i].name.toLowerCase().indexOf("xls") > -1 197 || files[i].name.toLowerCase().indexOf("xlsx") > -1 198 || files[i].name.toLowerCase().indexOf("pdf") > -1 199 ) { 200 if (i == 0) { 201 FirstIsFile = true; 202 } else { 203 OtherIsFile = true; 204 } 205 206 } else if (files[i].name.toLowerCase().indexOf("zip") > -1) { 207 if (i == 0) { 208 FirstIsFile = true; 209 } else { 210 OtherIsFile = true; 211 } 212 }else if (files[i].name.indexOf("jpeg") > -1 213 || files[i].name.toLowerCase().indexOf("png") > -1 214 || files[i].name.toLowerCase().indexOf("jpg") > -1 215 || files[i].name.toLowerCase().indexOf("gif") > -1 216 ) { 217 if (i == 0) { 218 FirstIsFile = false; 219 } else { 220 OtherIsFile = false; 221 } 222 223 } else { 224 res.IsPass = false; 225 226 } 227 if (files.length == 1) { 228 res.IsPass = true; 229 res.IsFile = FirstIsFile; 230 } else { 231 if (FirstIsFile != OtherIsFile) { 232 res.IsPass = false; 233 } else { 234 res.IsPass = true; 235 res.IsFile = FirstIsFile; 236 } 237 } 238 } 239 callback(res); 240 } 241 window.delFile = function (keyid, callback) 242 { 243 $.post("https://image.centaline-sc.com:/File/delete", { KeyId: keyid }, function (res) { 244 callback(res); 245 }) 246 } 247 248 /* 249 三个参数 250 file:一个是文件(类型是图片格式), 251 w:一个是文件压缩的后宽度,宽度越小,字节越小 252 objDiv:一个是容器或者回调函数 253 photoCompress() 254 */ 255 function photoCompress(file, w) { 256 257 var ready = new FileReader(); 258 /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/ 259 ready.readAsDataURL(file); 260 261 var p = new Promise(function (resolve, reject) { //做一些异步操作 262 ready.onload = function () { 263 var re = ready.result; 264 resolve(canvasDataURL(re, w)); 265 } 266 267 }); 268 return p; 269 //ready.onload = function () { 270 // var re = this.result; 271 // canvasDataURL(re, w, objDiv) 272 //} 273 274 275 } 276 277 function canvasDataURL(path, obj) { 278 var img = new Image(); 279 img.src = path; 280 var p = new Promise(function (resolve, reject) { //做一些异步操作 281 img.onload = function () { 282 var that = img; 283 // 默认按比例压缩 284 var w = that.width, 285 h = that.height, 286 scale = w / h; 287 w = obj.width || w; 288 h = obj.height || (w / scale); 289 var quality =0.1; // 默认图片质量为0.7 290 //生成canvas 291 var canvas = document.createElement('canvas'); 292 var ctx = canvas.getContext('2d'); 293 // 创建属性节点 294 var anw = document.createAttribute("width"); 295 anw.nodeValue = w; 296 var anh = document.createAttribute("height"); 297 anh.nodeValue = h; 298 canvas.setAttributeNode(anw); 299 canvas.setAttributeNode(anh); 300 ctx.drawImage(that, 0, 0, w, h); 301 // 图像质量 302 if (obj.quality && obj.quality <= 1 && obj.quality > 0) { 303 quality = obj.quality; 304 } 305 // quality值越小,所绘制出的图像越模糊 306 var base64 = canvas.toDataURL('image/jpeg', 0.9); 307 // 回调函数返回base64的值 308 resolve(base64); 309 } 310 311 }); 312 return p; 313 } 314 /** 315 * 将以base64的图片url数据转换为Blob 316 * @param urlData 317 * 用url方式表示的base64图片数据 318 */ 319 function convertBase64UrlToBlob(urlData) { 320 var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1], 321 bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); 322 while (n--) { 323 u8arr[n] = bstr.charCodeAt(n); 324 } 325 return new Blob([u8arr], { type: mime }); 326 } 327 328 })
甘于平凡,做一个甘于平凡的人,菜米油盐,生老病死。