cropper.js uploading the original images with coor

2019-09-14 20:22发布

I am using cropper.js. I would like to upload the original image and the cropped coordinates(x,y,width,height) not the cropped image. What is the preferred way to do that?

Thanks.

1条回答
Fickle 薄情
2楼-- · 2019-09-14 20:40

For the client side of this question, here is code I use to package up the crop box data and ship it off to the server. See esp:

formData.append('last_crop', JSON.stringify($imageBox.cropper('getCropBoxData')));

$('#crop_button').click(function(){
    // Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`.
    // Store crop coordinates to db for future visit.
    var canvas = $imageBox.cropper('getCroppedCanvas');
    canvas.toBlob(function (blob) {
        var formData = new FormData();
        formData.append('croppedImage', blob);  // 'croppedImage' is the sent filename
        formData.append('last_crop', JSON.stringify($imageBox.cropper('getCropBoxData')));

        $.ajax('{% url 'profile_crop_avatar' %}', {
            method: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: function () {
                console.log('Upload success');
            },
            error: function () {
                console.log('Upload error');
            }
        });
    }, "image/jpeg", 0.75);

    // Also update masthead image after crop
    $('#masthead-avatar').attr('src', canvas.toDataURL());
});

On the server side (Django) I handle and store the coords with:

# Save new image and crop coords to profile
p = request.user
p.last_crop_coords = request.POST.get('last_crop')
p.save()
查看更多
登录 后发表回答