問題描述:git
使用 cropper.js 剪裁圖片時, 調用 toBlob() 方法報錯github
$("#image").cropper('getCroppedCanvas').toBlob(function (blob){})
報錯信息:ajax
Uncaught TypeError: $(...).cropper(...).toBlob is not a functionapp
解決方法:ui
/* 使用二進制方式處理dataUrl */ function processData(dataUrl) { var binaryString = window.atob(dataUrl.split(',')[1]); var arrayBuffer = new ArrayBuffer(binaryString.length); var 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(imgType); // imgType爲上傳文件類型,即 file.type } else { console.log('版本太低,不支持上傳圖片'); } } return blob; }
最後調用代碼:url
$('#cutBtn').click(function() { var data = $('#image').cropper('getCroppedCanvas', { width: 300, // 裁剪後的長寬 height: 300 }), blob = processData(data.toDataURL()); var formData = new FormData(); formData.append('uploadImg', blob); $.ajax({ url: '/path/to/upload', method: "POST", data: formData, processData: false, contentType: false, success: function() { console.log('Upload success'); }, error: function() { console.log('Upload error'); } }); });
cropper.js 用法說明文檔 spa
https://github.com/fengyuanchen/cropperjs/blob/master/README.mdcode