问题描述:
使用 cropper.js 剪裁图片时, 调用 toBlob() 方法报错
$("#image").cropper('getCroppedCanvas').toBlob(function (blob){})
报错信息:
Uncaught TypeError: $(...).cropper(...).toBlob is not a function
解决方法:
/* 使用二进制方式处理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; }
最后调用代码:
$('#cutBtn').click(function() { var data = $('#image').cropper('getCroppedCanvas', { 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 用法说明文档
https://github.com/fengyuanchen/cropperjs/blob/master/README.md