<span id="mktg5"></span>

<i id="mktg5"><meter id="mktg5"></meter></i>

        <label id="mktg5"><meter id="mktg5"></meter></label>
        最新文章專題視頻專題問答1問答10問答100問答1000問答2000關(guān)鍵字專題1關(guān)鍵字專題50關(guān)鍵字專題500關(guān)鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關(guān)鍵字專題關(guān)鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
        問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
        當(dāng)前位置: 首頁 - 科技 - 知識(shí)百科 - 正文

        js移動(dòng)端圖片壓縮上傳功能

        來源:懂視網(wǎng) 責(zé)編:小采 時(shí)間:2020-11-27 22:28:57
        文檔

        js移動(dòng)端圖片壓縮上傳功能

        js移動(dòng)端圖片壓縮上傳功能:移動(dòng)端圖片壓縮上傳功能如何實(shí)現(xiàn)? 做移動(dòng)端開發(fā)的時(shí)候,form里面的file后臺(tái)經(jīng)常獲取不到,用foemdata也拿不到 找到了一個(gè)formdata的腳本 <!DOCTYPE html> <html lang=en> <head> <meta charset
        推薦度:
        導(dǎo)讀js移動(dòng)端圖片壓縮上傳功能:移動(dòng)端圖片壓縮上傳功能如何實(shí)現(xiàn)? 做移動(dòng)端開發(fā)的時(shí)候,form里面的file后臺(tái)經(jīng)常獲取不到,用foemdata也拿不到 找到了一個(gè)formdata的腳本 <!DOCTYPE html> <html lang=en> <head> <meta charset

        移動(dòng)端圖片壓縮上傳功能如何實(shí)現(xiàn)?

        做移動(dòng)端開發(fā)的時(shí)候,form里面的file后臺(tái)經(jīng)常獲取不到,用foemdata也拿不到

        找到了一個(gè)formdata的腳本

        <!DOCTYPE html>
        <html lang="en">
        <head>
         <meta charset="UTF-8">
         <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
         <title>移動(dòng)端圖片壓縮上傳demo</title>
         <style>
         *{margin: 0;padding: 0;}
         li{list-style-type: none;}
         a,input{outline: none;-webkit-tap-highlight-color:rgba(0,0,0,0);}
         #choose{display: none;}
         canvas{width: 100%;border: 1px solid #000000;}
         #upload{display: block;margin: 10px;height: 60px;text-align: center;line-height: 60px;border: 1px solid;border-radius: 5px;cursor: pointer;}
         .touch{background-color: #ddd;}
         .img-list{margin: 10px 5px;}
         .img-list li{position: relative;display: inline-block;width: 100px;height: 100px;margin: 5px 5px 20px 5px;border: 1px solid rgb(100,149,198);background: #fff no-repeat center;background-size: cover;}
         .progress{position: absolute;width: 100%;height: 20px;line-height: 20px;bottom: 0;left: 0;background-color:rgba(100,149,198,.5);}
         .progress span{display: block;width: 0;height: 100%;background-color:rgb(100,149,198);text-align: center;color: #FFF;font-size: 13px;}
         .size{position: absolute;width: 100%;height: 15px;line-height: 15px;bottom: -18px;text-align: center;font-size: 13px;color: #666;}
         .tips{display: block;text-align:center;font-size: 13px;margin: 10px;color: #999;}
         .pic-list{margin: 10px;line-height: 18px;font-size: 13px;}
         .pic-list a{display: block;margin: 10px 0;}
         .pic-list a img{vertical-align: middle;max-width: 30px;max-height: 30px;margin: -4px 0 0 10px;}
         </style>
        </head>
        <body>
        <input type="file" id="choose" accept="image/*" multiple>
        <ul class="img-list"></ul>
        <a id="upload">上傳圖片</a>
        <span class="tips">只允許上傳jpg、png及gif</span>
        <div class="pic-list">
         你上傳的圖片(圖片有效期為1分鐘):
        </div>
         
        <script src="https://www.gxlcms.com/public/jquery-2.1.1.min.js"></script>
        <script>
         var filechooser = document.getElementById("choose");
         // 用于壓縮圖片的canvas
         var canvas = document.createElement("canvas");
         var ctx = canvas.getContext('2d');
         // 瓦片canvas
         var tCanvas = document.createElement("canvas");
         var tctx = tCanvas.getContext("2d");
         var maxsize = 100 * 1024;
         $("#upload").on("click", function() {
         filechooser.click();
         })
         .on("touchstart", function() {
         $(this).addClass("touch")
         })
         .on("touchend", function() {
         $(this).removeClass("touch")
         });
         filechooser.onchange = function() {
         if (!this.files.length) return;
         var files = Array.prototype.slice.call(this.files);
         if (files.length > 9) {
         alert("最多同時(shí)只可上傳9張圖片");
         return;
         }
         files.forEach(function(file, i) {
         if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
         var reader = new FileReader();
         var li = document.createElement("li");
        // 獲取圖片大小
         var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
         li.innerHTML = '<div class="progress"><span></span></div><div class="size">' + size + '</div>';
         $(".img-list").append($(li));
         reader.onload = function() {
         var result = this.result;
         var img = new Image();
         img.src = result;
         $(li).css("background-image", "url(" + result + ")");
         //如果圖片大小小于100kb,則直接上傳
         if (result.length <= maxsize) {
         img = null;
         upload(result, file.type, $(li));
         return;
         }
        // 圖片加載完畢之后進(jìn)行壓縮,然后上傳
         if (img.complete) {
         callback();
         } else {
         img.onload = callback;
         }
         function callback() {
         var data = compress(img);
         upload(data, file.type, $(li));
         img = null;
         }
         };
         reader.readAsDataURL(file);
         })
         };
         // 使用canvas對(duì)大圖片進(jìn)行壓縮
         function compress(img) {
         var initSize = img.src.length;
         var width = img.width;
         var height = img.height;
         //如果圖片大于四百萬像素,計(jì)算壓縮比并將大小壓至400萬以下
         var ratio;
         if ((ratio = width * height / 4000000) > 1) {
         ratio = Math.sqrt(ratio);
         width /= ratio;
         height /= ratio;
         } else {
         ratio = 1;
         }
         canvas.width = width;
         canvas.height = height;
        // 鋪底色
         ctx.fillStyle = "#fff";
         ctx.fillRect(0, 0, canvas.width, canvas.height);
         //如果圖片像素大于100萬則使用瓦片繪制
         var count;
         if ((count = width * height / 1000000) > 1) {
         count = ~~(Math.sqrt(count) + 1); //計(jì)算要分成多少塊瓦片
        // 計(jì)算每塊瓦片的寬和高
         var nw = ~~(width / count);
         var nh = ~~(height / count);
         tCanvas.width = nw;
         tCanvas.height = nh;
         for (var i = 0; i < count; i++) {
         for (var j = 0; j < count; j++) {
         tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
         ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
         }
         }
         } else {
         ctx.drawImage(img, 0, 0, width, height);
         }
         //進(jìn)行最小壓縮
         var ndata = canvas.toDataURL('image/jpeg', 0.1);
         console.log('壓縮前:' + initSize);
         console.log('壓縮后:' + ndata.length);
         console.log('壓縮率:' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
         tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
         return ndata;
         }
         // 圖片上傳,將base64的圖片轉(zhuǎn)成二進(jìn)制對(duì)象,塞進(jìn)formdata上傳
         function upload(basestr, type, $li) {
         var text = window.atob(basestr.split(",")[1]);
         var buffer = new Uint8Array(text.length);
         var pecent = 0, loop = null;
         for (var i = 0; i < text.length; i++) {
         buffer[i] = text.charCodeAt(i);
         }
         var blob = getBlob([buffer], type);
         var xhr = new XMLHttpRequest();
         var formdata = getFormData();
         formdata.append('imagefile', blob);
         xhr.open('post', '/cupload');
         xhr.onreadystatechange = function() {
         if (xhr.readyState == 4 && xhr.status == 200) {
         var jsonData = JSON.parse(xhr.responseText);
         var imagedata = jsonData[0] || {};
         var text = imagedata.path ? '上傳成功' : '上傳失敗';
         console.log(text + ':' + imagedata.path);
         clearInterval(loop);
         //當(dāng)收到該消息時(shí)上傳完畢
         $li.find(".progress span").animate({'width': "100%"}, pecent < 95 ? 200 : 0, function() {
         $(this).html(text);
         });
         if (!imagedata.path) return;
         $(".pic-list").append('<a href="' + imagedata.path + '" rel="external nofollow" >' + imagedata.name + '(' + imagedata.size + ')<img src="' + imagedata.path + '" /></a>');
         }
         };
         //數(shù)據(jù)發(fā)送進(jìn)度,前50%展示該進(jìn)度
         xhr.upload.addEventListener('progress', function(e) {
         if (loop) return;
         pecent = ~~(100 * e.loaded / e.total) / 2;
         $li.find(".progress span").css('width', pecent + "%");
         if (pecent == 50) {
         mockProgress();
         }
         }, false);
         //數(shù)據(jù)后50%用模擬進(jìn)度
         function mockProgress() {
         if (loop) return;
         loop = setInterval(function() {
         pecent++;
         $li.find(".progress span").css('width', pecent + "%");
         if (pecent == 99) {
         clearInterval(loop);
         }
         }, 100)
         }
         xhr.send(formdata);
         }
         /**
         * 獲取blob對(duì)象的兼容性寫法
         * @param buffer
         * @param format
         * @returns {*}
         */
         function getBlob(buffer, format) {
         try {
         return new Blob(buffer, {type: format});
         } catch (e) {
         var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
         buffer.forEach(function(buf) {
         bb.append(buf);
         });
         return bb.getBlob(format);
         }
         }
         /**
         * 獲取formdata
         */
         function getFormData() {
         var isNeedShim = ~navigator.userAgent.indexOf('Android')
         && ~navigator.vendor.indexOf('Google')
         && !~navigator.userAgent.indexOf('Chrome')
         && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
         return isNeedShim ? new FormDataShim() : new FormData()
         }
         /**
         * formdata 補(bǔ)丁, 給不支持formdata上傳blob的android機(jī)打補(bǔ)丁
         * @constructor
         */
         function FormDataShim() {
         console.warn('using formdata shim');
         var o = this,
         parts = [],
         boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
         oldSend = XMLHttpRequest.prototype.send;
         this.append = function(name, value, filename) {
         parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
         if (value instanceof Blob) {
         parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
         parts.push(value);
         }
         else {
         parts.push('\r\n\r\n' + value);
         }
         parts.push('\r\n');
         };
         // Override XHR send()
         XMLHttpRequest.prototype.send = function(val) {
         var fr,
         data,
         oXHR = this;
         if (val === o) {
         // Append the final boundary string
         parts.push('--' + boundary + '--\r\n');
         // Create the blob
         data = getBlob(parts);
         // Set up and read the blob into an array to be sent
         fr = new FileReader();
         fr.onload = function() {
         oldSend.call(oXHR, fr.result);
         };
         fr.onerror = function(err) {
         throw err;
         };
         fr.readAsArrayBuffer(data);
         // Set the multipart content type and boudary
         this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
         XMLHttpRequest.prototype.send = oldSend;
         }
         else {
         oldSend.call(this, val);
         }
         };
         }
        </script>
        </body>
        </html>

        聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

        文檔

        js移動(dòng)端圖片壓縮上傳功能

        js移動(dòng)端圖片壓縮上傳功能:移動(dòng)端圖片壓縮上傳功能如何實(shí)現(xiàn)? 做移動(dòng)端開發(fā)的時(shí)候,form里面的file后臺(tái)經(jīng)常獲取不到,用foemdata也拿不到 找到了一個(gè)formdata的腳本 <!DOCTYPE html> <html lang=en> <head> <meta charset
        推薦度:
        標(biāo)簽: 圖片 上傳 移動(dòng)
        • 熱門焦點(diǎn)

        最新推薦

        猜你喜歡

        熱門推薦

        專題
        Top
        主站蜘蛛池模板: 成人午夜免费福利| 成人毛片免费观看视频大全| 国产免费AV片无码永久免费| 亚洲精华国产精华精华液网站| 在线观看AV片永久免费| 日韩亚洲产在线观看| 麻豆精品国产免费观看| 精品一区二区三区免费毛片| 亚洲精品国产日韩无码AV永久免费网 | 亚洲精品久久久久无码AV片软件| 日韩精品无码区免费专区| 亚洲日韩中文字幕无码一区| 国产青草视频免费观看97 | 亚洲精品乱码久久久久久蜜桃| 男女男精品网站免费观看| 亚洲愉拍一区二区三区| 日本视频免费在线| 深夜免费在线视频| 亚洲国产精品无码专区影院| 精品免费人成视频app| 亚洲6080yy久久无码产自国产| 免费看国产一级片| 日本高清不卡aⅴ免费网站| 亚洲高清无在码在线电影不卡| 久久这里只有精品国产免费10| 在线看亚洲十八禁网站| 亚洲国产一二三精品无码| 青娱乐免费在线视频| 免费激情网站国产高清第一页 | 99久久人妻精品免费二区| 亚洲成人激情小说| 亚洲中文无韩国r级电影| 9277手机在线视频观看免费| 日韩色视频一区二区三区亚洲| 亚洲AV午夜成人影院老师机影院| 美丽的姑娘免费观看在线播放| 精品特级一级毛片免费观看| 亚洲天堂久久精品| 国产免费观看青青草原网站| 最近免费中文字幕mv电影| 男人扒开添女人下部免费视频|