Reputation: 3282
I have a form which contains two input type="file" fields and a submit button. One of the file fields will be user cropped, the other one will not. The cropping plugin I am using is cropbox. I have the basic user interface set up, but I don't understand how I can send the form data with the cropped image and uncropped image through Ajax to PHP. Here's a jsfiddle of what I have so far.
HTML
<form class="image_form" action="" method="post" enctype="multipart/form-data">
<input type="file" id="cropimage">
<input type="file">
<input type="submit" value="submit">
</form>
jQuery
$(function() {
$("#cropimage").on('change', function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function() {
var $img = $('<img />').attr({
src: reader.result
});
$img.on('load', function() {
$img.cropbox({
width: 600,
height: 400
}).on('cropbox', function(event, results, img) {
submission(JSON.stringify(results));
});
});
$('body').append($img);
};
reader.readAsDataURL(file);
});
});
function submission(get_data) {
$(".image_form").submit(function(e) {
e.preventDefault();
console.log(get_data);
$.ajax({
type: 'POST',
url: '',
data: new FormData(this),
processData: false,
contentType: false,
success: function(data) {
}
});
});
}
Once the user has uploaded an image, it'll check if the submit button has been pressed to send through Ajax. How can I send the cropped image through Ajax and not the original image?
Upvotes: 1
Views: 1210
Reputation: 6312
When using FormData
you can append Blob
with resized image directly to it.
CropBox plugin has getBlob
method which can be used to get blob with cropped image. All you need is to append blob to your formData:
formData.append('croppedFile', imageBlob)
// or if you want to add filename
formData.append('croppedFile', imageBlob, 'cropped.jpg')
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append https://github.com/acornejo/jquery-cropbox#methods
Upvotes: 1