From: https://www.cnblogs.com/ww03/p/9507039.htmlhtml
目標實現:前端
一、選擇圖片, 前端預覽效果jquery
二、圖片大於1.2M的時候, 對圖片進行壓縮ajax
三、以表單的形式上傳圖片數據庫
四、圖片刪除json
預覽效果圖:canvas
代碼說明:app
一、input:file選擇圖片ide
<!-- html部分 --> <ul id="preview" class="clear"> <li class="fl"> <img src="/images/audition/icon_upload.png"> <input id="fileImage" type="file" name="file[]" multiple /> <div class="num">0/4</div> </li> </ul>
var imgId = 0; //圖片id標誌, 方便刪除預覽圖片 /* 選擇圖片 */ function choosePic() { $('#fileImage').change(function() { var files = this.files, len = $('#preview').find('.pic').length; if (len + files.length > 4) { showTip('最多隻能上傳4張圖片哦~'); return; } for (var i = 0; i < files.length; i++) { var file = files[i]; if (file.type.indexOf("image") == 0) { if (file.size >= 1024 * 1024 * 3) { showTip('圖片大小過大,應小於3M'); } else { showPic(file); //圖片預覽 } } else { showTip('文件"' + file.name + '"不是圖片類型') break; } } }); }
二、圖片預覽(base64)函數
/* 渲染圖片 */ function showPic(file) { var html = '', $wap = $('#preview'), reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e) { var image_base64 = this.result; html = '<li class="fl pic" id="imgItem_' + imgId + '">' + '<img src="' + image_base64 + '" alt="">' + '<i class="del-img"></i>' + '</li>'; imgId++; $wap.append(html); $('#fileImage').next().text($wap.find('.pic').length + '/4'); //圖片壓縮上傳,大於1.2M壓縮圖片 if (file.size / 1024 > 1024 * 1.2) { dealImage(image_base64, { quality: 0.5 }, function(base64Codes) { var bl = processData(base64Codes, file.type); uploadPic(bl, imgId); }); } else { uploadPic(file, imgId); } } }
三、圖片壓縮
/** * 圖片壓縮(利用canvas) * @param path 圖片路徑 * @param obj 壓縮配置width,height,quality,不傳則按比例壓縮 * @param callback 回調函數 */ function dealImage(path, obj, callback) { var img = new Image(); img.src = path; img.onload = function() { var that = this; // 默認按比例壓縮 var w = that.width, h = that.height, scale = w / h; w = obj.width || w; h = obj.height || (w / scale); //生成canvas var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'); canvas.width = w; canvas.height = h; ctx.drawImage(that, 0, 0, w, h); // 默認圖片質量爲0.7 var quality = 0.7; if (obj.quality && obj.quality <= 1 && obj.quality > 0) { quality = obj.quality; } // 回調函數返回base64的值 var base64 = canvas.toDataURL('image/jpeg', quality); callback(base64); } }
壓縮後的文件是base64格式, 咱們但願用file圖片的形式上傳
/* 將以base64的圖片url數據轉換爲Blob */ function processData(dataUrl, type) { var binaryString = window.atob(dataUrl.split(',')[1]), arrayBuffer = new ArrayBuffer(binaryString.length), intArray = new Uint8Array(arrayBuffer); for (var i = 0, j = binaryString.length; i < j; i++) { intArray[i] = binaryString.charCodeAt(i); } var data = [intArray], blob; try { blob = new Blob(data); } catch (e) { window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; if (e.name === 'TypeError' && window.BlobBuilder) { var builder = new BlobBuilder(); builder.append(arrayBuffer); blob = builder.getBlob(type); } else { showTip('版本太低,不支持圖片壓縮上傳'); } } return blob; }
四、圖片上傳
/* 上傳圖片 */ function uploadPic(file, id) { var formData = new FormData(); formData.append('img', file); $.ajax({ url: '/upload', type: 'post', dataType: 'json', data: formData, contentType: false, processData: false, success: function(res){ if(res.respCode == 1000) { $('#imgItem_' + id).find('.del-img').attr('data-src', res.data.src); }else { showTip('文件上傳失敗!'); } } }); }
五、其餘
function showTip(str) { //TODO:信息提示 console.log(str); }
/* 刪除圖片 */ function delPic() { var $wap = $('#preview'); $wap.on('click', '.del-img', function() { //TODO:從數據庫刪除圖片 $(this).parent().remove(); $('#fileImage').next().text($wap.find('.pic').length + '/4'); }); }
源碼:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>前端圖片預覽壓縮上傳</title> 6 <style> 7 .clear::after { 8 content: ''; 9 clear: both; 10 display: block; 11 } 12 .fl { 13 float: left; 14 } 15 .list-img li { 16 position: relative; 17 margin-right: 10px; 18 list-style: none; 19 } 20 .list-img img { 21 display: inline-block; 22 width: 50px; 23 height:50px; 24 } 25 .list-img input { 26 position: absolute; 27 top: 0; 28 left: 0; 29 z-index: 10; 30 width: 50px; 31 height:50px; 32 opacity: 0; 33 } 34 .list-img i { 35 position: absolute; 36 top: 0; 37 right: 0; 38 width: 15px; 39 height: 15px; 40 background: url(../images/icon_del.png) no-repeat center; 41 background-size: 100%; 42 } 43 .list-img .num { 44 position: absolute; 45 left: 0; 46 bottom: 0; 47 width: 100%; 48 text-align: center; 49 color: #999; 50 font-size: 12px; 51 } 52 </style> 53 </head> 54 <body> 55 <div class="list-img"> 56 <ul id="preview" class="clear">