Croppie result to send to web server - javascript

Can someone please help me with this?
I'm not that versed at JavaScript and I've read the documentation over and over plus reviewed as many posts here as well as googled the problem. I'm not able to get my cropped result and send it to my web server. Here's my code.
HTML:
<form action="" method="post" enctype="multipart/form-data" id="formTest">
<div id="modal">
<div id="main-cropper"></div>
<a class="button actionUpload">
<span>Upload</span>
<input type="file" id="upload" value="Choose Image"
accept="image/*" name="imgf">
</a>
<button class="actionDone">Done</button>
<button class="actionCancel">Cancel</button>
</div>
</form>
JS:
<script>
var basic = $('#main-cropper').croppie({
viewport: { width: 300, height: 400, type: 'square' },
boundary: { width: 700, height: 500 },
showZoomer: true
});
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#main-cropper').croppie('bind', {
url: e.target.result
});
$('.actionDone').toggle();
$('.actionUpload').toggle();
}
reader.readAsDataURL(input.files[0]);
}
}
$('.actionUpload input').on('change', function () { readFile(this); });
$('.actionDone').on('click', function(){
$('#main-cropper').croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$('#formTest').find('name=["imgf"]').val('src', resp);
});
$('.actionDone').toggle();
$('.actionUpload').toggle();
});
</script>

I did some additional research and found a solution through using AJAX. I tried it and it works. Need to do some clean up on the CSS but that's nothing major. Here is some of the modified code:
partial JavaScript:
$('.crop_image').click(function(event){
image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response){
$.ajax({
url:"upload.php",
type: "POST",
data:{"image": response},
success:function(data)
{
$('#uploadimageModal').modal('hide');
$('#uploaded_image').html(data);
}
});
})
});
AJAX:
if(isset($_POST["image"]))
{
$data = $_POST["image"];
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = time() . '.png';
file_put_contents("pg/$imageName", $data);
echo '<img src="'.$imageName.'" class="img-thumbnail" />';
}
https://www.webslesson.info/2018/03/image-crop-and-upload-using-jquery-with-php-ajax.html

Related

I can't use JQuery Plugin Croppie. Getting "croppie is not a function" error

I'm trying to crop the image before uploading and I'm using Croppie.js plugin but I don't know I'm getting "Uncaught TypeError: $(...).croppie is not a function" this error in console.
I tried to use this plugin at the end of the file just before the body and also tried in the head and between the html but I'm getting the same error. I don't know why this is happening.
Here's my code.
<script src="jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/croppie/croppie.css" />
<script type="text/javascript">
$(document).ready(function(){
$image_crop = $('#upload-image').croppie({
enableExif: true,
viewport: {
width: 200,
height: 200,
type: 'square'
},
boundary: {
width: 300,
height: 300
}
});
$('#userPhoto').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
$image_crop.croppie('bind', {
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('#crop').on('click', function (ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (response) {
$.ajax({
url: "upload.php",
type: "POST",
data: {"image":response},
success: function (data) {
html = '<img src="' + response + '" />';
$("#upload-image-i").html(html);
}
});
});
});
});
</script>
I've tried all the code in a single file and it's working fine there.
I faced the same problem. Check the CDN.
You have to use two links (croppie.css and croppie.min.js) to the page where you are trying to upload the image.
CDN
https://cdnjs.com/libraries/croppie

Compressor.js - Upload image via normal form submission (no Ajax)

I'm using the following script to compress images on the client side before uploading:
https://github.com/fengyuanchen/compressorjs
I can upload the images fine via Ajax using the following code:
// Following is a form with #name and #image input fields and #submit button:
var formData = new FormData();
$('#image').change(function(e) {
var img = e.target.files[0];
new Compressor(img, {
quality: 0.8,
maxWidth: 1600,
maxHeight: 1600,
success(result) {
formData.append('image', result, result.name);
},
});
});
$('#submit').click(function() {
formData.append('name', $('#name').val());
$.ajax({
type: 'POST',
url: 'form-script.php',
data: formData,
contentType: false,
processData: false
}).done(function() {
});
});
I need to upload the image via normal form submission -no Ajax-, but I couldn't manage to do it. I am asking how to use result in the following code, so that the compressed image will be submitted when the form is submitted. As a side note, I use PHP server side.
$('#image').change(function(e) {
var img = e.target.files[0];
new Compressor(img, {
quality: 0.7,
maxWidth: 1200,
maxHeight: 1200,
success(result) {
// ??
},
});
});
Thank you.
After further research and trial, I was able to find how to post the compressed image without Ajax, using the following:
Form:
<form id="form" action="" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name">
<input type="file" id="image">
<!-- A hidden input is needed to put the image data after compression. -->
<input type="hidden" id="image-temp" name="image">
<input type="submit" name="submit" value="Submit">
</form>
Image compression:
$('#image').change(function(e) {
var img = e.target.files[0];
new Compressor(img, {
quality: 0.8,
maxWidth: 1600,
maxHeight: 1600,
success(result) {
var reader = new FileReader();
reader.readAsDataURL(result);
reader.onloadend = function() {
var base64data = reader.result;
$('#image-temp').val(base64data);
}
},
});
});
Server side (PHP):
if (isset($_POST['submit'])) {
/* Get other form data as usual. */
$name = $_POST['name'];
if (!empty($_POST['image'])) {
file_put_contents('images/image.jpg', file_get_contents($_POST['image']));
}
}
Use what you want for directory (images/) and file name (image.jpg) as you wish.
For multiple images, use HTML/CSS classes for JS part, and a loop for PHP part.
there is another solution too;
launchUpload(e) {
const that = this;
new Compressor(e.target.files[0], {
quality: 0.6,
maxWidth: 250,
minWidth: 250,
success(compressedResult){
that.init(compressedResult)
},
error(err) {
console.log(err.message);
},
})
}
init(file) {
this.compressed = file;
},

How to check that file is not selected in Croppie

I use croppie to crop photos on my website. I am able to crop and upload the image. But when I try to crop and upload without selecting an image, a black image is being uploaded. So how do I validate if the file upload is empty? (Note: I use Codeigniter)
HTML:
<div class="form-group">
<div id="upload-image"></div>
</div>
<div class="form-group">
<label for="">Select profile image:</label>
<input type="file" id="images" class="form-control">
<button class="btn btn-success cropped_image help-block"><i class="fa fa-floppy-o"></i> Save</button>
</div>
JS:
$image_crop = $('#upload-image').croppie({
enableExif: true,
viewport: {
width: 342,
height: 192,
type: 'square'
},
boundary: {
width: 380,
height: 250
}
});
$('#images').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
$image_crop.croppie('bind', {
url: e.target.result
}).then(function(){
// console.log('<?php echo base_url() ?>');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.cropped_image').on('click', function (ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: { width: 1366, height: 768 }
}).then(function (response) {
$.ajax({
url: "<?php echo base_url() ?>Light/upload_home_bg",
type: "POST",
data: {"image":response},
success: function (data) {
alert(data);
$(location).attr('href','<?php echo base_url() ?>Light/home');
// html = '<img src="' + response + '" />';
// $("#upload-image-i").html(html);
}
});
});
});
PHP:
public function upload_home_bg()
{
$path = 'uploads/'.$this->data['account']->username.'/';
$croped_image = $_POST['image'];
list($type, $croped_image) = explode(';', $croped_image);
list(, $croped_image) = explode(',', $croped_image);
$croped_image = base64_decode($croped_image);
$image_name = time().'.png';
// upload cropped image to server
file_put_contents($path.$image_name, $croped_image);
$query = $this->db->query("select * from contents where user_id = '$this->user_id' and id = '$this->id' and meta_key = 'home_background_image'");
if ($query->num_rows() > 0)
{
$data['home_bg'] = $query->row();
$Bg = [
'value' => base_url().$path.$image_name
];
if ($this->Lights->update_home_background_image($Bg,$this->user_id,$data['home_bg']->content_id))
{
echo "Image successfully updated!";
}
}
else
{
$Bg = [
'user_id' => $this->user_id,
'id' => $this->id,
'business_name' => $this->BusinessName,
'meta_key' => 'home_background_image',
'content_title' => '',
'description' => '',
'value' => base_url().$path.$image_name
];
if ($this->db->insert('contents',$Bg))
{
echo "Image successfully uploaded!";
}
}
}
I tried doing this to check if the user selected an image:
if (!empty($_POST['image'])) {
# code...
}
But there are data being passed regardless if the user selected an image or not. Here is the data being passed (on the alert window): https://i.stack.imgur.com/DtqFD.png
Thanks in advance!
Okay. I finally managed to come up with a solution. What I did was to pass another value on my ajax var file_input = $('#images').val(); which gets the value of my file upload input.
JS:
$('.cropped_image').on('click', function (ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: { width: 1366, height: 768 }
}).then(function (response) {
var file_input = $('#images').val();
$.ajax({
url: "<?php echo base_url() ?>Light/upload_home_bg",
type: "POST",
data: {"image":response,"file":file_input},
success: function (data) {
alert(data);
$(location).attr('href','<?php echo base_url() ?>Light/home');
}
});
});
});
Then on my php file, I check if the file is empty or not:
if (!empty($this->input->post('file')))
{
//Upload code
}
else
{
//Prompt user to select an image
}
late to the party - similar problem. I added this before the ajax:
...}).then(function (response) {
if(response.length < 2000){
if(! confirm("Did you load an image? It looks too small\n"+ response.length)) return;
}
FWIW an empty image for me is of length 1971

croppie plug-in does not work using ajax /innerHtml content

I'm using croppie plug-in but does not work when content is overwritten using ajax/php (result show with innerHtml). What I should doing? Please help me!
read more about croppie: https://foliotek.github.io/Croppie/
Content of data.php : Compilation of php and html code
<?php
if(isset($_POST['id']) && $_POST['id'] == 1){
?>
<div id="upload-demo" style="width:350px"></div>
<strong>Select Image:</strong>
<br/>
<input type="file" id="upload">
<?php
}
?>
My Codes:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://demo.itsolutionstuff.com/plugin/croppie.js"></script>
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/croppie.css">
</head>
<body>
<div id="div1"></div>
<button>Get External Content</button>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'get',
url: 'php/data.php',
data: {
id: '1'
},
success: function(response) {
document.getElementById("div1").innerHTML = response;
}
});
});
});
$uploadCrop = $('#upload-demo').croppie({
enableExif: true,
viewport: {
width: 200,
height: 200,
type: 'circle'
},
boundary: {
width: 300,
height: 300
}
});
$('#upload').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
</script>
</body>
</html>
Your problem will be solved with the following code:
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'get',
url: 'php/data.php',
data: {
id: '1'
},
success: function(response) {
document.getElementById("div1").innerHTML = response;
}
});
});
});
var $uploadCrop;
$uploadCrop = $('#upload-demo').croppie({
enableExif: true,
viewport: {
width: 200,
height: 200,
type: 'circle'
},
boundary: {
width: 300,
height: 300
}
});
$(document).on('change', '#upload', function () {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
</script>

How can I create the callback in ajax form?

How can I create the callback after a file is upload on the server?
I want to upload a file on a server after a JS function call.
I want to call the function addDownload and after this function is complete, then call the next javascript function. How can I do this?
I have a following source code:
HTML:
<form id="imageform" method="post" enctype="multipart/form-data" action="actions/downloadsadd.php">
<strong>File: </strong><input name="photoimg" id="photoimg" style="width: 100px;" type="file" />
Select Image: <br />
<div id="divPreview"></div>
</form>
Javascript:
addDownload: function ()
{
$("#divPreview").html('');
$("#divPreview").html('<img src="Images/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#divPreview'
}).submit();
},
PHP - downloads.php:
public function addDownloads() {
$db = new DB();
$db->connect();
$path = "../../images/upload/files/";
$valid_formats = array("php", "phtml", "php3", "php4", "js", "shtml", "pl", "py", "html", "exe", "bat", "htm", "sql");
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if (strlen($name)) {
list($txt, $ext) = explode(".", $name);
if (!in_array($ext, $valid_formats)) {
if ($size < (1024 * 1024)) { // Image size max 1 MB
$actual_image_name = time() . "." . $ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if (move_uploaded_file($tmp, $path . $actual_image_name)) {
$arr = array(
'file' => $actual_image_name
);
dibi::query('INSERT INTO [downloads]', $arr);
echo "FILE:" .$actual_image_name;
}
else
echo "Failed upload!";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
}
}
Just guessing, but your code seems use the jQuery form plugin:
$("#imageform").ajaxForm(...);
The plugin allows you to add a callback function using the success option. This function will be invoked when the AJAX request (i.e. all the code in the PHP file you're calling) has finished successfully.
$("#imageform").ajaxForm({
target: '#divPreview',
data: {
var1: $("#inputText").val() //assuming #inputText is a text field
},
success: function() {
alert("Callback!");
}
}).submit();
See the documentation for further reference.
I did like this to upload avatar.
<script type="text/javascript">
$('input[id=lefile]').change(function() {
$('#photoCover').val($(this).val());
});
function doUpload(){
//Use FormData to get files in form.
var formData = new FormData($("#myform")[0]);
$.ajax({
url: $('#myform').attr('action'),
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
},
error: function (returndata) {
alert(returndata);
}
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="avatar-content">
<form id="myform" action="http://www.example.com/editor/" method=post enctype=multipart/form-data>
<input id="lefile" type="file" name="file" style="display:none">
<div class="input-append">
<input id="photoCover" type="text" class="form-control" style="height:34px; width: 54%; display: inline-block;" onclick="$('input[id=lefile]').click();">
<div class="btn btn-primary btn-file" onclick="doUpload()">
<i class="fa fa-upload"></i> Upload
</div>
</div>
</form>
</div>

Categories

Resources