Problem Description:
When cropping images using cropper.js, call the toBlob() method to report an error
$("#image").cropper('getCroppedCanvas').toBlob( function (blob){})
Error message:
Uncaught TypeError: $(…).cropper(…).toBlob is not a function
Solution:
/* Use binary method to process 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 is the upload file type, that is, file.type } else { console.log( 'The version is too low to support uploading pictures' ); } } return blob; }
Finally call the code:
$('#cutBtn').click( function () { var data = $('#image').cropper('getCroppedCanvas' , { width: 300, // length and width after cropping 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 usage documentation
https://github.com/fengyuanchen/cropperjs/blob/master/README.md