How to send cropped image with form post - javascript

How can I handle cropped image and send with post? I am using Cropper.js library. The HTML codes already in a form element. These codes copied from sample admin template. Cropping works but I cant send files.
HTML:
<div class="row">
<div class="col-md-6">
<div class="image-crop">
<img src="{{ asset('backend/images/image-upload.png') }}">
</div>
</div>
<div class="col-md-6">
<h4>Preview image</h4>
<div class="img-preview img-preview-sm" style="width: 180px;height:180px;"></div>
<hr>
<div class="btn-group">
<button class="btn btn-white" id="zoomIn" type="button">Zoom In</button>
<button class="btn btn-white" id="zoomOut" type="button">Zoom Out</button>
<button class="btn btn-white" id="rotateLeft" type="button">Rotate Left</button>
<button class="btn btn-white" id="rotateRight" type="button">Rotate Right</button>
</div>
<hr>
<div class="btn-group">
<label title="Upload image file" for="inputImage" class="btn btn-primary">
<input type="file" accept="image/*" name="file" id="inputImage" class="hide">
Upload new image
</label>
<label title="Donload image" id="download" class="btn btn-primary">Download</label>
</div>
</div>
JS:
var $image = $(".image-crop > img")
$($image).cropper({
aspectRatio: 1,
preview: ".img-preview",
done: function(data) {
// Output the result data for cropping image.
}
});
var $inputImage = $("#inputImage");
if (window.FileReader) {
$inputImage.change(function() {
var fileReader = new FileReader(),
files = this.files,
file;
if (!files.length) {
return;
}
file = files[0];
if (/^image\/\w+$/.test(file.type)) {
fileReader.readAsDataURL(file);
fileReader.onload = function () {
$inputImage.val("");
$image.cropper("reset", true).cropper("replace", this.result);
};
} else {
alert("Please upload a image file");
}
});
} else {
$inputImage.addClass("hide");
}
//Disabled Cropped Image Download
/*
$("#download").click(function() {
window.open($image.cropper("getDataURL"));
});
*/
PHP:
var_dump($_FILES);
Post Output:

you do it as a canvas first and get the base64 string toDataURL("image/png") then catch it in your server side and convert it to image again using the base64 string
kindly take a look at this post.
Convert an image into binary data in javascript

Related

How to preview image when upload to multiple forms

I have 2 image upload forms, when one is uploaded it should show a preview of the uploaded image. However, when I upload an image in one of the input forms, both forms display a preview of the last uploaded image. How do I make the preview only appear on the uploaded form?
Here's my code :
<div class="container">
<form action="save.php" method="post" enctype="multipart/form-data">
<!-- rows -->
<div class="row">
<div class="col-sm-6">
<img src="images/80x80.png" id="preview1" class="img-thumbnail1">
<div class="form-group">
<div id="msg"></div>
<input type="file" name="img1" class="file1" id="file1">
<div class="input-group my-3">
<div class="input-group-append">
<button type="button" id="select_image1" class="browse btn btn-dark">select image</button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<img src="images/80x80.png" id="preview2" class="img-thumbnail2">
<div class="form-group">
<div id="msg"></div>
<input type="file" name="img2" class="file2" id="file2">
<div class="input-group my-3">
<div class="input-group-append">
<button type="button" id="select_image2" class="browse btn btn-dark">select image</button>
</div>
</div>
</div>
</div>
</div>
<button type="submit" name="btn_save" class="btn btn-success">Save</button>
</form>
</div>
<script>
$(document).on("click", "#select_image1", function() {
var file = $(this).parents().find(".file1");
file.trigger("click");
});
$('input[type="file"]').change(function(e) {
var fileName1 = e.target.files[0].name;
$("#file1").val(fileName1);
var reader = new FileReader();
reader.onload = function(e) {
// get loaded data and render thumbnail.
document.getElementById("preview1").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(e.target.files[0]);
});
// 2
$(document).on("click", "#select_image2", function() {
var file2 = $(this).parents().find(".file2");
file2.trigger("click");
});
$('input[type="file"]').change(function(el) {
var fileName2 = el.target.files[0].name;
$("#file2").val(fileName2);
var reader2 = new FileReader();
reader2.onload = function(el) {
// get loaded data and render thumbnail.
document.getElementById("preview2").src = el.target.result;
};
// read the image file as a data URL.
reader2.readAsDataURL(el.target.files[0]);
});
</script>
I've tried changing the script code, but it doesn't work. Please help. Thank you.

Update Crop Image with cropper js in Laravel don't work before upload

i've a problem with my code. I use Spatie Media library and cropper.js for crop the image before upload in the db. When i upload a form, the crop is fine, the preview too. But when i save the image in the folder and db the pics not resize. He crop only if don't move or resize the element. Can you help me?
Blade.php
<form enctype="multipart/form-data" action="{{route('admin.users.changeAvatar', $user->id)}}" method="POST" class="avatar-upload">
#csrf
<div class="avatar-edit">
<input type='file' id="imageUpload" accept=".png, .jpg, .jpeg" name="avatar" class=" imageUpload" />
<input type="hidden" name="base64image" name="base64image" id="base64image">
<label for="imageUpload"></label>
</div>
<div class="avatar-preview container2">
<div id="imagePreview" style="background-image:url('/uploads/avatars/{{ $user->avatar }}');">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="hidden" name="media" value="{{ $user->media }}">
<input style="margin-top: 60px;" type="submit" class="btn btn-danger">
</div>
</div>
</form>
<div class="modal fade bd-example-modal-lg imagecrop" id="model" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="img-container">
<div class="row">
<div class="col-md-11">
<img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary crop" id="crop">Crop</button>
</div>
</div>
</div>
</div>
Controller changeAvatar.php
dd(json_decode($request->file('avatar')));
$user = User::find($id);
$avatar = $request->file('avatar');
DB::table('user_avatars')
->where('user_id', $user->id)
->update([
'path' => $request->file('avatar')->getClientOriginalName(),
'extension' => $request->file('avatar')->getClientOriginalExtension(),
'size' => $request->file('avatar')->getSize(),
'mime' => $request->file('avatar')->getClientMimeType()
]);
$user->addMediaConversion($avatar);
if ($request->hasFile('avatar')) {
$user->clearMediaCollection('avatar');
User::first()
->addMedia($avatar)
->toMediaCollection('avatar');
}
notify()->success('Avatar Changed Successfully!', 'User');
return back();
Cropper Js
<script>
var $modal = $('.imagecrop');
var image = document.getElementById('image');
var cropper;
$("body").on("change", ".imageUpload", function(e){
var files = e.target.files;
var done = function(url) {
image.src = url;
$modal.modal('show');
};
var reader;
var file;
var url;
if (files && files.length > 0) {
file = files[0];
if (URL) {
done(URL.createObjectURL(file));
} else if (FileReader) {
reader = new FileReader();
reader.onload = function(e) {
done(reader.result);
};
reader.readAsDataURL(file);
}
}
});
$modal.on('shown.bs.modal', function() {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 1,
});
}).on('hidden.bs.modal', function() {
cropper.destroy();
cropper = null;
});
$("body").on("click", "#crop", function() {
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
canvas.toBlob(function(blob) {
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
$('#base64image').val(base64data);
document.getElementById('imagePreview').style.backgroundImage = "url("+base64data+")";
$modal.modal('hide');
}
});
})
</script>

Upload or Draw Signature on Laravel form

I used this https://www.itsolutionstuff.com/post/laravel-signature-pad-example-tutorialexample.html to create a signature pad. I am looking for a way to add an option to upload a signature or use the pad to draw a signature.
Here's what I wrote:
Laravel Blade Code
<form method="POST" action="{{ route('signaturepad.upload') }}">
<div class="tab-content">
<div class="tab-pane fade show active" id="draw">
<div class="col-md-12">
<label class="" for="">Draw Signature:</label>
<br/>
<div id="sig"></div>
<br><br>
<button id="clear" class="btn btn-danger">Clear Signature</button>
{{--<button class="btn btn-success">Save</button>--}}
<textarea id="signature" name="signature" style="display: none"></textarea>
</div>
</div>
<div class="tab-pane fade" id="upload">
<label class="" for="">Upload Signature:</label>
{{--<div class="form-group"></div>
<input type="file" name="file" id="file" required>--}}
{{--<button type="submit">Submit</button>--}}
</div>
<button class="btn btn-success">Save</button>
</div>
</form>
Javascript
<script src="{{ asset('js/pages/jquery.signature.js')}}"></script>
<script type="text/javascript">
var sig = $('#sig').signature({syncField: '#signature', syncFormat: 'PNG'});
$('#clear').click(function(e) {
e.preventDefault();
sig.signature('clear');
$("#signature").val('');
});
</script>
Controller
if(!empty($request->input('signature')) || (!empty($request->input('file')))) {
echo $request->signature;
echo $request->file;
dd('passed');
//$folderPath = public_path('uploads/');
//$data_uri = $request->signature;
//$encoded_image = explode(",", $data_uri)[1];
//$decoded_image = base64_decode($encoded_image);
//$file = $folderPath . uniqid();
//file_put_contents($file, $decoded_image);
return view('dashboard');
} else {
//dd('Signature is empty.');
return back()->withErrors(['msg', 'Signature Empty']);
}
Drawing the Signature works when one of the file uploads is commented out. When both are active they don't post and both don't work. My question is how do I work with both where one can either draw or upload the signature. I have tried if statements in the controller to no avail.
Thanks in Advance!

I can't reset input file inside form after submit

I have a form with some fields and after submit finish i want to reset whole form but only reset input text areas not input type file.
I check every similar questions and solutions but none of them work for me.Some solutions refresh page which i don't want that.
<form class=" dropzone px-5" id="mydropzone">
<h2 class="text-center">Lets create your menu</h2>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCalories">Calorie</label>
<input type="text" class="form-control" id="inputCalories" required>
</div>
<div class="form-group col-md-6">
<label for="cc">Calorie Calculator</label>
<button id="cc" class="btn btn-primary btn-lg"><i class="fas fa-calculator mr-2"></i>Click Me</button>
</div>
</div>
<div class="form-row">
<div class="form-group ml-2 col-sm-6">
<label>Menu Item Image</label>
<div id="msg"></div>
<div class="progress" id="uploader">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%"></div>
</div>
<input type="file" name="img[]" class="file" accept="image/*" id="fileButton">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file" required>
<div class="input-group-append">
<button type="button" class="browse btn btn-primary"><i class="fas fa-folder-open mr-2"></i>Browse...</button>
</div>
</div>
<div class="ml-2 col-sm-6">
<img src=" " id="preview" class="img-thumbnail">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block mb-3">Submit Menu</button>
<!-- -------------------------------------------------------------------------- -->
</div>
</form>
And my create menu which clear all fields after form submit.
// create menu
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file = e.target.files[0];
var storageRef = firebase.storage().ref('foodImg/' + file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
console.error(error);
}, function() {
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
const createMenuForm = document.querySelector('#mydropzone');
createMenuForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('restaurants').add({
foodLine: {
menuTitle: createMenuForm.menuTitle.value
},
food: {
foodName: createMenuForm.foodName.value,
imageURL: downloadURL,
inputCalories: createMenuForm.inputCalories.value,
menuItemDescription: createMenuForm.menuItemDescription.value,
menuItemInfo: createMenuForm.menuItemInfo.value
}
}).then(() => {
//reset form
createMenuForm.reset();
fileButton.value = "";
var preview = document.getElementById('preview');
preview.value = "";
}).catch(err => {
console.log(err.message);
});
});
});
});
});
Can you try these things also
document.getElementById("myForm").reset();
$("#myForm").trigger("reset");
I think you try to access createMenuForm outside the scope where const createMenuForm was declared.
Try to declare it above the event listener:
// create menu
const createMenuForm = document.querySelector('#mydropzone');
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// ...
or directly with
document.querySelector('#mydropzone').reset();
i debug and find that preview need to be clean
document.getElementById("preview").src = "#";

Image can not be displayed after upload using Angular.js

I have an issue. I can not display image after selecting using ng-file-upload from Angular.js. I have to upload multiple file here. I am explaining my code below.
<div ng-repeat="mul in mulImage">
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Image{{$index+1}}:</span>
<div>
<input type="file" class="filestyle form-control" data-size="lg" name="upload_{{$index}}" id="bannerimage_{{$index}}" ng-model="file" ngf-pattern="'image/*'" accept="image/*" ngf-max-size="2MB" custom-on-change="uploadFile" ngf-select="onFileSelect($index,$file);">
<div style="clear:both;"></div>
</div>
<span class="input-group-btn" ng-show="mulImage.length>0">
<img ng-src="{{attchImage}}" name="pro" border="0" style="width:32px; height:32px; border:#808080 1px solid;" ng-if="mul.image !=null">
<input type="button" class="btn btn-success" name="plus" id="plus" value="+" ng-click="addNewImageRow(mulImage);" ng-show="$last"> <input type="button" class="btn btn-danger" name="minus" id="minus" value="-" ng-show="mulImage.length>1" ng-click="deleteNewImageRow(mulImage,$index);">
</span>
</div>
</div>
my controller side code is given below.
$scope.uploadFile = function(event) {
console.log('event', $scope.mulImage.length);
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(file);
}
};
$scope.imageIsLoaded = function(e) {
$scope.$apply(function() {
$scope.attchImage = e.target.result;
});
}
Here i need after selecting the image it should display inside image tag but failed to do that. Here is my plunkr code. Please help me to resolve this issue.
You used 'onFileSelect' in your view and defined $scope.onFileSelect1.
If I edit it the plunkersample runs for me.
Or am I missing something?

Categories

Resources