取得3525558f8f338d4ea90ebf22e5cde2bc上傳的檔案;
<input id="imgUpload" type="file" onchange="addPic" accept="image/*" />當input檔案觸發change
function addPic(e){ if (typeof FileReader === 'undefined') { return alert('你的浏览器不支持上传图片哟!'); } var files = e.target.files || e.dataTransfer.files; if(files.length > 0){ imgResize(file[0], callback); } }
function imgResize(file, callback){ var fileReader = new FileReader(); fileReader.onload = function(){ var IMG = new Image(); IMG.src = this.result; IMG.onload = function(){ var w = this.naturalWidth, h = this.naturalHeight, resizeW = 0, resizeH = 0; // maxSize 是压缩的设置,设置图片的最大宽度和最大高度,等比缩放,level是报错的质量,数值越小质量越低 var maxSize = { width: 500, height: 500, level: 0.6 }; if(w > maxSize.width || h > maxSize.height){ var multiple = Math.max(w / maxSize.width, h / maxSize.height); resizeW = w / multiple; resizeH = w / multiple; } else { // 如果图片尺寸小于最大限制,则不压缩直接上传 return callback(file) } var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'); if(window.navigator.userAgent.indexOf('iPhone') > 0){ canvas.width = resizeH; canvas.height = resizeW; ctx.rorate(90 * Math.PI / 180); ctx.drawImage(IMG, 0, -resizeH, resizeW, resizeH); }else{ canvas.width = resizeW; canvas.height = resizeH; ctx.drawImage(IMG, 0, 0, resizeW, resizeH); } var base64 = canvas.toDataURL('image/jpeg', maxSize.level); convertBlob(window.atob(base64.split(',')[1]), callback); } }; fileReader.readAsDataURL(file); }將base64的資料轉換成一個Blob物件
function convertBlob(base64, callback){ var buffer = new ArrayBuffer(base64.length); var ubuffer = new Uint8Array(buffer); for (var i = 0; i < base64.length; i++) { ubuffer[i] = base64.charCodeAt(i) } var blob; try { blob = new Blob([buffer], {type: 'image/jpg'}); } catch (e) { window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; if(e.name === 'TypeError' && window.BlobBuilder){ var blobBuilder = new BlobBuilder(); blobBuilder.append(buffer); blob = blobBuilder.getBlob('image/jpg'); } } callback(blob) }使用
function callback(fileResize){ var data = new FormData(); data.append('file', fileResize); var config = { headers: {'Content-Types': 'multipart/form-data'} }; // 这里用的es6语法发起请求,可以无视 axios.post(url, data, config).then().catch(e){} }
以上是分享利用HTML5實作圖片壓縮上傳的實例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!