Handle AJAX request on the Same Page – PHP - javascript

I'm trying to create an image cropping tool, it should upload a pic, crop it and print it on the page as a image.jpg not as a base 64 (data:image)
As I know it cannot be done through HTML and javascript.
So I was trying to do this through PHP. I'm uploading and croping the image but I can't catch the result, upload it to the server and print it on the page as a image.jpg
Here is my code, please help
<div id="upload-demo"></div>
<div class="col-md-4" style="padding:5%;">
<strong>Select image to crop:</strong>
<input type="file" id="image">
<button class="btn btn-success btn-block btn-upload-image" style="margin-top:2%">Upload Image</button>
</div>
<script type="text/javascript">
var resize = $('#upload-demo').croppie({
enableExif: true,
enableOrientation: true,
viewport: { // Default { width: 100, height: 100, type: 'square' }
width: 200,
height: 200,
type: 'circle' //square
},
boundary: {
width: 300,
height: 300
}
});
$('#image').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
resize.croppie('bind',{
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.btn-upload-image').on('click', function (ev) {
resize.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (img) {
$.ajax({
type: "POST",
data: {form_submit: 1,"image":img},
success: function (data) {
html = '<img src="' + img + '" />';
$("#preview-crop-image").html(html);
}
});
});
});
</script>
<?php
if(isset($_POST['form_submit'])) {
$imageProcess = 0;
if(is_array($_FILES)) {
$fileName = $_FILES['image']['tmp_name'];
$sourceProperties = getimagesize($fileName);
$resizeFileName = time();
$uploadPath = "./uploads/";
$fileExt = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$uploadImageType = $sourceProperties[2];
$sourceImageWidth = $sourceProperties[0];
$sourceImageHeight = $sourceProperties[1];
move_uploaded_file($fileName, $uploadPath. $resizeFileName. ".". $fileExt);
$imageProcess = 1;
}
if($imageProcess == 1){
?>
<img src="<?php echo $uploadPath.$resizeFileName.'.'. $fileExt; ?>" width="700" height="700" >
<h4><b>Thump Image</b></h4>
<?php
}else{
?>
<div class="alert icon-alert with-arrow alert-danger form-alter" role="alert">
<i class="fa fa-fw fa-times-circle"></i>
<strong> Note !</strong> <span class="warning-message">Invalid Image </span>
</div>
<?php
}
$imageProcess = 0;
}
?>

<div id="upload-demo"></div>
<div class="col-md-4" style="padding:5%;">
<strong>Select image to crop:</strong>
<input type="file" id="image">
<button class="btn btn-success btn-block btn-upload-image" style="margin-top:2%">Upload Image</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.3/croppie.js" type="text/javascript"></script>
<script type="text/javascript">
var resize = $('#upload-demo').croppie({
enableExif: true,
enableOrientation: true,
viewport: { // Default { width: 100, height: 100, type: 'square' }
width: 200,
height: 200,
type: 'circle' //square
},
boundary: {
width: 300,
height: 300
}
});
$('#image').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
resize.croppie('bind',{
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.btn-upload-image').on('click', function (ev) {
alert(111);
resize.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (img) {
$.ajax({
type: "POST",
data: {form_submit: 1,"image":img},
success: function (data) {
html = '<img src="' + img + '" />';
$("#preview-crop-image").html(html);
}
});
});
});
</script>
<?php
if(isset($_POST['form_submit'])) {
$imageProcess = 0;
if(is_array($_FILES)) {
$fileName = $_FILES['image']['tmp_name'];
$sourceProperties = getimagesize($fileName);
$resizeFileName = time();
$uploadPath = "./uploads/";
$fileExt = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$uploadImageType = $sourceProperties[2];
$sourceImageWidth = $sourceProperties[0];
$sourceImageHeight = $sourceProperties[1];
move_uploaded_file($fileName, $uploadPath. $resizeFileName. ".". $fileExt);
$imageProcess = 1;
}
if($imageProcess == 1){
?>
<img src="<?php echo $uploadPath.$resizeFileName.'.'. $fileExt; ?>" width="700" height="700" >
<h4><b>Thump Image</b></h4>
<?php
}else{
?>
<div class="alert icon-alert with-arrow alert-danger form-alter" role="alert">
<i class="fa fa-fw fa-times-circle"></i>
<strong> Note !</strong> <span class="warning-message">Invalid Image </span>
</div>
<?php
}
$imageProcess = 0;
}
?>
try this it should work

Related

upload files and show preview of each file with options like rotate and remove for each file on front view and while uploading show progress bar

I am using laravel 8 for my project. The problem is: I need preview of files selected from user before upload with options rotate and remove file. I had built these options but these were working fine with single file and not with multiple file. I was working initially with js/jquery for these appearances but when these did not give appropriate output, I tried to use the ajax.. It is throwing many other problems and I am stuck now..I need to keep option of drag and drop method and get and save file to google drive and dropbox too.. could anyone help or guide please...
below is the code for reference I was working till now..
**DocumentController:**
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;
use ZipArchive;
use Mpdf\Mpdf;
use setasign\Fpdi;
ini_set('max_execution_time', 600); // 10 minutes
class DocumentController extends Controller
{
public function display_preview(Request $req)
{
echo "working";print_r($req->file('fileList'));dd('preview can be set.');
foreach($req->fileList as $key=>$f)
{
$name=basename($f);
$fname=pathinfo($name, PATHINFO_FILENAME);
echo $file_preview="<div class='preview_box alert' style='height: 180px; width: 150px !important; align-content: center;background-Color: lightblue;margin:5px auto;' id='preview_box".$key."'> <button type='button' name='rot_btn' class='r_btn' id='r_btn".$key."' class='align-items-center' name='rotation_style_Right'> <img src='{{url('assets/images/Rotate_icon.jpg')}}' style='backface-visibility: inherit;height:20px;width:20px;'> </button> <button type='button' style='float: right;' class='closebox close' data-dismiss='alert' id='closebox".$key."'>×</button> <div class='thumbnail_pdf' id='thumbnail_pdf".$key."'> <object data='{{url('assets/img/docx-icon-11.jpg')}}' style='height:35px; width:35px;align-self: center;margin: auto;' ></object> </div><div id='thumbnail_word' style='word-wrap: break-word;'>". $name ."</div></div> ";
}
}
public function convertUserUploadedWordToPdf(Request $req)
{
print_r($req->all());dd('test');
$this->validate($req, [
'file' => 'required',
'file.*' => 'mimes:doc,docx'
]);
$doc_pdf=array();
if($req->hasFile('file'))
{
foreach ($req->file('file') as $key => $doc)
{
$name = basename($_FILES['file']['name'][$key]); // $file is set to name without extension
$fname=pathinfo($name, PATHINFO_FILENAME);
$ext=pathinfo($name,PATHINFO_EXTENSION);
$doc->move(public_path('uploads/PDF/'), $_FILES['file']['name'][$key]);
/* Set the PDF Engine Renderer Path */
$domPdfPath = base_path('vendor/dompdf/dompdf');
\PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
\PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');
//Load word file and convert into pdf
$Content = \PhpOffice\PhpWord\IOFactory::load(public_path('uploads/PDF/'.$name));
//Save it into PDF
$PDFWriter = \PhpOffice\PhpWord\IOFactory::createWriter($Content,'PDF');
//$file = basename($_FILES['file']['name'][$key], ".docx"); // $file is set to name without extension
$PDFWriter->save(public_path('uploads/PDF/'.$fname.'.pdf')); //PDF Generated
if($req->input('rotation_angle'))
{
$rotation_angle=$req->input('rotation_angle');
$rotation_angle=360-$rotation_angle;
$mpdf = new Mpdf();// Rotating file
$pagecount = $mpdf->setSourceFile(public_path('uploads/PDF/'.$fname.'.pdf'));
for($i=1;$i<=$pagecount;$i++)
{
$tplId = $mpdf->ImportPage($i);
//$mpdf->UseTemplate($tplId);
$size = $mpdf->getTemplateSize($tplId);
if ($size['width'] > $size['height'] && ($rotation_angle == 90 || $rotation_angle== 270))
{
$orientation='P';
// Font size 1/3 Height if it landscape
//$fontsize = $size['height'] / 3;
}
elseif($size['width'] > $size['height'] && ($rotation_angle == 0 || $rotation_angle== 180))
{
$orientation='L';
}
elseif($size['width'] < $size['height'] && ($rotation_angle == 0 || $rotation_angle== 180))
{
$orientation='P';
}
else
{
$orientation='L';
// Font size 1/3 Width if it portrait
//$fontsize = $size['width'] / 3;
}
$mpdf->AddPage($orientation);
//Find the middle of the page to use as a pivot at rotation.
$mX = $size['width'] / 2;
$mY = $size['height'] / 2;
// Set the transparency of the text to really light
$mpdf->SetAlpha(1);
$mpdf->StartTransform();
$mpdf->Rotate($rotation_angle, $mX, $mY);
$mpdf->UseTemplate($tplId);
$mpdf->SetXY(0, $mY);
$mpdf->StopTransform();
// Reset the transparency to default
$mpdf->SetDefaultBodyCSS('transform','rotate('.$rotation_angle.'deg)');
$mpdf->SetAlpha(1);
}
$mpdf->Output(public_path('uploads/PDF/'.$fname.'_r.pdf'));
array_push($doc_pdf,$fname.'_r.pdf');
}
else
{
array_push($doc_pdf,$fname.'.pdf') ;
}
}
if(count($req->file('file'))>1)
{
//print_r($doc_pdf);die;
$zipFileName = 'pdf_docx.zip';
$zip = new ZipArchive();
if ($zip->open(public_path('uploads/PDF/'.$zipFileName),ZipArchive::CREATE) === TRUE)
{
// Add File in ZipArchive
foreach($doc_pdf as $file)
{
if (! $zip->addFile(public_path('uploads/PDF/'.$file),$file))
{
echo 'Could not add file to ZIP: ' . $file;
}
}
$zip->close();
}
else
{
echo 'Could not open ZIP file.';
}
return back()
->with('success','You have successfully converted files.')
->with('file',$zipFileName);
}
else
{
if($req->input('rotation_angle'))
{
return back()
->with('success','You have successfully converted file.')
->with('file',$fname.'_r.pdf');
}
else
{
return back()
->with('success','You have successfully converted file.')
->with('file',$fname.'.pdf');
}
}
}
}
public function pdfview($pdf_file)
{
$filePath = public_path('uploads/PDF/'.$pdf_file);
$headers = ['Content-Type: application/octet-stream'];
$fileName = $pdf_file;
return response()->download($filePath, $fileName, $headers);
}
public function insertPdfConversion()
{
return view('pdf_conversion');
}
Route:(web.php)
//Word to pdf Conversion..
Route::get('/pdf_conversion', [App\Http\Controllers\DocumentController::class, 'insertPdfConversion'])->name('pdf_conversion');
Route::post('/pdf_conversion',[App\Http\Controllers\DocumentController::class, 'convertUserUploadedWordToPdf'])->name('wordtopdf_conversion');
Route::post('/get_preview',[App\Http\Controllers\DocumentController::class,'display_preview'])->name('get_preview');
$router->get('/pdfview/{pdf_file}',[
'uses' => 'App\Http\Controllers\DocumentController#pdfview',
'as' => 'pdfview'
]);
blade file:
#include('header1');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
.Add_file{
color: white;
}
.Add_file::-webkit-file-upload-button {
visibility: hidden;
}
.Add_file::before{
content: '+';
align-content: center;
display: inline-block;
background-image: linear-gradient(to top, blue, pink);
white-space: nowrap;
border: 1px solid #999;
border-radius: 30px;
outline: none;
cursor: pointer;
-webkit-user-select: none;
font-size: 30px;
height: 60px;
width: 60px;
}
.Add_file:hover::before {
border-color: black;
}
.Add_file:active::before {
background-image: -webkit-linear-gradient(to top, white, blue);
}
.file_input {
color:white;
}
.file_input::-webkit-file-upload-button {
visibility: hidden;
}
.file_input::before{
content: 'Select Word files';
align-content: center;
display: inline-block;
background-image: linear-gradient(to top, blue, pink);
white-space: nowrap;
border: 1px solid #999;
border-radius: 5px;
padding: 5px 8px;
outline: none;
cursor: pointer;
-webkit-user-select: none;
text-shadow: 1px 1px #fff;
text-align: center;
font-weight: 400;
font-size: 18pt;
min-height: 50px;
min-width: 250px;
}
.file_input:hover::before {
border-color: black;
}
.file_input:active::before {
background-image: -webkit-linear-gradient(to top, white, blue);
}
.dropzone {
height: 100px!important;
width: 250px;
align-content: center;
border: 1px solid grey;
}
.thumbnail_pdf{
height: 100px;
width: 70px;
align-self:center;
background-color: white;
align-content: center;
border-radius: 2px;
margin:auto;
}
.disabledbutton {
pointer-events: none;
opacity: 0.4;
}
</style>
<!-- Main Work Area-->
<div style="width:100%;min-height:auto;align-content:center;text-align: center;margin:15% 0%;">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<h1 style="text-align: center;">Convert WORD to PDF</h1>
<h4 style="text-align: center;">Make DOC and DOCX files easy to read by converting them to PDF.</h4>
<form class="form-group" method="POST" action="{{ route('wordtopdf_conversion') }}" enctype="multipart/form-data" id="dropForm">
<meta name="csrf-token" content="{{ csrf_token() }}">
<div class="row">
#csrf
<div class="col-sm-12 mt-4 align-items-center ">
<div class="form-group d-flex justify-content-center align-items-center" id="choose_file">
<input type="file" name="file[]" id="imgInp" class="file_input" accept=".doc,.docx" multiple="" >
<input type="text" name="rotation_angle" id="rot_ang" value="" hidden>
</div>
<span>
#if ($downloadpdf = Session::get('file'))
<a class="btn btn-primary align-items-center" href="{!! route('pdfview', ['pdf_file'=>$downloadpdf]) !!}" target="_blank">Download PDF</a>
#endif
</span>
</div>
</div>
<div class="row">
<div class="col-sm-5 col-md-5 " >
<div id="preview-template"></div>
<div class="row" id="files_preview" style="margin:auto;" ></div>
</div>
<div class="ad_files col-md-2 col-sm-2" style="display:none;min-width:20%;min-height:60%;align-content:center;float:right;margin:0 auto;">
<input type="file" name="file[]" id="ad_doc" class="Add_file" accept=".doc,.docx" multiple="" >
</div>
<div id="tools" class="form-group col-sm-4 col-md-4" style="float:right; display:none;">
<div class="card" style="height: 100%;width: 80%;margin: 0px;float: right;padding: 0px;">
<div class="card-header">
<span class="center-block">Word to PDF</span>
</div>
<div class="card-body">
</div>
<div class="card-footer">
<div class="form-group">
<!--<input type="submit" name="Conversions" id="startUpload" class="btn btn-primary" value="Convert Word To PDF ">-->
<button type="submit" name="Conversions" id="startUpload" class="btn btn-primary">
Convert Word To PDF <img src="{{url('assets/images/arrow.png')}}" style="height:30px;width: 30px;backface-visibility: hidden;">
</button>
</div>
</div>
</div>
</div>
</div>
</form>
<!-- The fileinput-button span is used to style the file input field as button -->
<!--<button id="uploadFile">Upload Files</button>-->
</div>
<!-- Work area ended-->
<script>
/*function rotateRight()
{
rotation += 90; // add 90 degrees, you can change this as you want
if (rotation == 360) {
// 360 means rotate back to 0
rotation = 0;
}
var img = document.querySelector('#thumbnail_pdf');
img.style.transform = 'rotate('+rotation+'deg)';
document.querySelector("#rot_ang").value=rotation;
}*/
//Disabling autoDiscover
/*Dropzone.autoDiscover = false;
$(function() {
//Dropzone class
var myDropzone = new Dropzone(".dropzone", {
url:"{{ route('wordtopdf_conversion') }}",
paramName: "file",
addRemoveLinks: true,
maxFilesize: 10,
maxFiles: 10,
acceptedFiles: ".doc,.docx",
autoProcessQueue: false
});
$('#tools').css("display","block");
$('#r_btn').css("display","block");
$('#choose_file').css("display","none");
$('#thumbnail_word').innerHTML=myDropzone.files.name;
$('#preview_box').css("display","block");
$('#preview_box').css("backgroundColor","lightblue");
$('#startUpload').click(function(){
myDropzone.processQueue();
});
});*/
//..... Dropzone Script is started..
var dropzone = new Dropzone('#dropForm', {
previewTemplate: document.querySelector('#preview-template').innerHTML,
parallelUploads: 5,
thumbnailHeight: 220,
thumbnailWidth: 220,
multipleUpload:true,
maxFilesize: 5,
filesizeBase: 1000,
autoQueue:true,
thumbnail: function(file, dataUrl) {
if (file.previewElement) {
file.previewElement.classList.remove("dz-file-preview");
var images = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
for (var i = 0; i < images.length; i++) {
var thumbnailElement = images[i];
thumbnailElement.alt = file.name;
thumbnailElement.src = dataUrl;
}
setTimeout(function() { file.previewElement.classList.add("dz-image-preview"); }, 1);
}
$('#thumbnail_word').innerHTML = myDropzone.files.name;
}
});
// Now fake the file upload, since GitHub does not handle file uploads
// and returns a 404
var minSteps = 6,
maxSteps = 60,
timeBetweenSteps = 100,
bytesPerStep = 100000;
dropzone.uploadFiles = function(files) {
var self = this;
for (var i = 0; i < files.length; i++) {
var file = files[i];
totalSteps = Math.round(Math.min(maxSteps, Math.max(minSteps, file.size / bytesPerStep)));
for (var step = 0; step < totalSteps; step++) {
var duration = timeBetweenSteps * (step + 1);
setTimeout(function(file, totalSteps, step) {
return function() {
file.upload = {
progress: 100 * (step + 1) / totalSteps,
total: file.size,
bytesSent: (step + 1) * file.size / totalSteps
};
self.emit('uploadprogress', file, file.upload.progress, file.upload.bytesSent);
if (file.upload.progress == 100) {
file.status = Dropzone.SUCCESS;
self.emit("success", file, 'success', null);
self.emit("complete", file);
self.processQueue();
//document.getElementsByClassName("dz-success-mark").style.opacity = "1";
}
};
}(file, totalSteps, step), duration);
}
}
}
//----DropZone Script is ended..
$(document).ready(function()
{
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
doc_arr = [];
//if (window.File && window.FileList && window.FileReader)
//{
$("#imgInp").on("change", function(e)
{
//var files1 = e.target.files;
var files1 = $(this).val();
alert(files1)
$.ajax({
type:'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('get_preview')}}",
data:{ // change data to this object
_token : $('meta[name="csrf-token"]').attr('content'),
fileList:files1
},
dataType: "text",
success:function(result)
{
alert(result)
$('#files_preview').append(result);
$('#tools').css('display','block');
$('#imgInp').css('display','none');
$('.ad_files').css('display',"block");
},
error: function (request, message, error)
{
//handleException(request, message, error);
alert('error in process');
alert(error);
},
cache: false,
contentType: false,
processData: false
})
/*for (var i = 0; i < files1.length; i++)
{
//alert(files1[i].name)
var a = files1[i];
//var fileReader = new FileReader();
//fileReader.onload = (function(e)
//{
//var file = e.target.files;
file_preview="<div class='preview_box alert' style='height: 180px; width: 150px !important; align-content: center;background-Color: lightblue;margin:5px auto;' id='preview_box"+i+"'> <button type='button' name='rot_btn' class='r_btn' id='r_btn"+i+"' class='align-items-center' name='rotation_style_Right'> <img src='{{url('assets/images/Rotate_icon.jpg')}}' style='backface-visibility: inherit;height:20px;width:20px;'> </button> <button type='button' style='float: right;' class='closebox close' data-dismiss='alert' id='closebox"+i+"'>×</button> <div class='thumbnail_pdf' id='thumbnail_pdf"+i+"'> <object data='{{url('assets/img/docx-icon-11.jpg')}}' style='height:35px; width:35px;align-self: center;margin: auto;' ></object> </div><div id='thumbnail_word' style='word-wrap: break-word;'>"+ a.name +"</div></div> ";
$('#files_preview').append(file_preview);*/
/*
const doc = {
Name: a.name,
Rotation: rotation,
file_detail: function() {
return this.Name + " : " + this.Rotation;
}
};
doc_arr[i]= doc.file_detail();*/
$('.closebox').click(function()
{
//files1[i].name="";
/*
if(files1.length == 0)
{
$("#tools").addClass("disabledbutton");
}
else
{
$("#tools").removeClass("disabledbutton");
} */
})
//});
//fileReader.readAsDataURL(a);
//}
})
//}
let rotation = 0;
$('button[name=rot_btn]').click(function()
{
alert(123) //rotateRight()
rotation += 90; // add 90 degrees, you can change this as you want
if (rotation == 360)
{
// 360 means rotate back to 0
rotation = 0;
}
$(this).siblings('.thumbnail_pdf').css('transform','rotate('+rotation+'deg)');
a=$(this).siblings('.thumbnail_word').innerHTML;
//doc_arr.push( a+' : '+rotation);
//docJSON = JSON.stringify(doc_arr);
$('#rot_ang').val(a+' : '+rotation);
});
})
/*
function load_features()
{
const [file] = imgInp.files;
var fullPath = $("#imgInp").val();
var filename = fullPath.replace(/^.*[\\\/]/, '');
document.getElementById('thumbnail_word').innerHTML = filename;
document.getElementById('tools').style.display = "block";
document.getElementById('r_btn').style.display = "block";
document.querySelector('#imgInp').style.display = "none";
document.getElementById('preview_box').style.display = "block";
document.getElementById('preview_box').style.backgroundColor = "lightblue";
document.querySelector('.ad_files').style.display = "block";
}*/
</script>
#include('footer');

Cropping and uploading image with Croppie jquery plugin

cropping and uploading image using Croppie plugin working fine sample code as follows
<html lang="en">
<head>
<title>PHP and jQuery - Crop Image and Upload using Croppie plugin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
<style>
.croppie-container .cr-vp-circle
{
border-radius:0
}
.cr-slider-wrap
{
display:none
}
</style>
</head>
<body>
<div class="container">
<div class="card" style="max-height: 500px;">
<div class="card-header bg-info" style="display:none">PHP and jQuery - Crop Image and Upload using Croppie plugin</div>
<div class="card-body">
<div class="row">
<div class="col-md-4 text-center">
<div id="upload-demo"></div>
</div>
<div class="col-md-4" style="padding:5%;">
<strong>Select image to crop:</strong>
<input type="file" id="image">
<button class="btn btn-success btn-block btn-upload-image" style="margin-top:2%">Upload Image</button>
</div>
<div class="col-md-4" style="background: #9d9d9d;">
<div id="preview-crop-image" style="background: #fff;
width: 200px;
margin: 50px 72px;
height: 200px;"></div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var resize = $('#upload-demo').croppie({
enableExif: true,
enableOrientation: true,
viewport: { // Default { width: 100, height: 100, type: 'square' }
width: 200,
height: 200,
type: 'square' //square
},
boundary: {
width: 300,
height: 300
}
});
$('#image').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
resize.croppie('bind',{
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.btn-upload-image').on('click', function (event) {
resize.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (img) {
alert(img)
$.ajax({
url: "cropping.php",
type: "POST",
data: {"image":img},
success: function (data) {
html = '<img src="' + img + '" />';
$("#preview-crop-image").html(html);
}
});
});
});
</script>
</body>
</html>
But the result from croppie plugin is getting as canvas i.e base64 but we want the result from croppie plugin as same as file upload so that we can access the cropped image with $_FILES, how it can be achieved please suggest us.
Croppie is using canvas.drawImage(...) to manipulate images so you can not upload the images as you upload a file using a file input field. What you can do is, submit the base64 encoded string and reconstruct(base64 decode) the image in your server.
$imageName = $uuid.".png";
// extracting the base64 encoded string from the request payload
$imageArray = explode(";", $_POST['imagebase64']);
$imageContents = explode(",", $imageArray[1]);
$imagebase64 = base64_decode($imageContents[1]);
// saving the image to a temp file
$tempPath = sys_get_temp_dir()."/".$imageName;
file_put_contents($tempPath, $imagebase64);
Now you have the uploaded image saved in $tempPath

Progress bar for the form

I'm trying to create a progress bar for my form but it still doesn't work. After loading the form, I would like my progress bar to move from 0 percent to 100 and finish loading. I still can't see why my progress bar is not working.
My code looks like this
<form method="POST" enctype="multipart/form-data" name="newProductForm" id="newProductForm">
<input type="file" name="img" class="custom-input-file" accept=".jpg, .jpeg" required id="id_img">
<input type="text" name="category" class="form-control form-control-emphasized" id="category" placeholder="Wpisz kategorie..." maxlength="200" required>
<div class="progress">
<div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
0%
</div>
</div>
<button type="button" onClick="submitFunction();" class="btn btn-block btn-primary" id="buttonSubmitProduct">
<span style="display:block;" id="buttonText">
Submit
</span>
<span style="display:none;" id="buttonSipner">
Loading......
</span>
</button>
</form>
My AJAX and JS:
<script>
function submitFunction() {
document.getElementById('buttonSubmitProduct').disabled = true;
document.getElementById('buttonText').style.display = 'none';
document.getElementById('buttonSipner').style.display = 'block';
document.getElementById('newProductForm').submit();
}
$(document).ready(function() {
$('newProductForm').on('submit', function(event) {
event.preventDefault();
var formData = new FormData($('newProductForm')[0]);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
console.log('Bytes Loaded: ' + e.loaded);
console.log('Total Size: ' + e.total);
console.log('Percentage Uploaded: ' + (e.loaded / e.total))
var percent = Math.round((e.loaded / e.total) * 100);
$('#progressBar').attr('aria-valuenow', percent).css('width', percent + '%').text(percent + '%');
}
});
return xhr;
},
type: 'POST',
url: '',
data: formData,
processData: false,
contentType: false,
success: function() {
location.replace("/?okey=smile");
}
});
});
});
</script>
I don't see any errors in the console. Why is my code not working?
What about use the progress HTML5 tag to do that?
//calling the function in window.onload to make sure the HTML is loaded
window.onload = function() {
var pos = 0;
var t = setInterval(move, 75);
function move() {
if(pos >= 400) {
clearInterval(t);
}
else {
pos += 4;
bar.value = pos/4;
}
}
};
#container {
width: 400px;
height: 50px;
position: relative;
}
#bar {
width: 400px;
height: 50px;
position: absolute;
}
progress {
text-align: center;
}
progress:after {
content: attr(value)'%';
}
progress:before {
content: 'progress ';
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="container">
<progress id="bar" value="0" max="100"></progress>
</div>
</body>
</html>

CROPPER JS Get cropper canvas not working with larger files

I am using https://github.com/fengyuanchen/cropperjs/ but it has a problem in getCroppedCanvas function ,
It's working just fine with small images but not showing when it comes to larger images
result.appendChild(cropper.getCroppedCanvas());
I am using this live example https://fengyuanchen.github.io/cropperjs/examples/upload-cropped-image-to-server.html; source code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Cropper.js</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<link rel="stylesheet" href="../css/cropper.css">
<style>
.label {
cursor: pointer;
}
.progress {
display: none;
margin-bottom: 1rem;
}
.alert {
display: none;
}
.img-container img {
max-width: 100%;
}
</style>
</head>
<body>
<div class="container">
<h1>Upload cropped image to server</h1>
<label class="label" data-toggle="tooltip" title="Change your avatar">
<img class="rounded" id="avatar" src="https://avatars0.githubusercontent.com/u/3456749?s=160" alt="avatar">
<input type="file" class="sr-only" id="input" name="image" accept="image/*">
</label>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
</div>
<div class="alert" role="alert"></div>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Crop the image</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">
<img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="crop">Crop</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.bundle.min.js"></script>
<script src="https://fengyuanchen.github.io/cropperjs/js/cropper.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
var avatar = document.getElementById('avatar');
var image = document.getElementById('image');
var input = document.getElementById('input');
var $progress = $('.progress');
var $progressBar = $('.progress-bar');
var $alert = $('.alert');
var $modal = $('#modal');
var cropper;
$('[data-toggle="tooltip"]').tooltip();
input.addEventListener('change', function (e) {
var files = e.target.files;
var done = function (url) {
input.value = '';
image.src = url;
$alert.hide();
$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: 3,
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
document.getElementById('crop').addEventListener('click', function () {
var initialAvatarURL;
var canvas;
$modal.modal('hide');
if (cropper) {
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
initialAvatarURL = avatar.src;
avatar.src = canvas.toDataURL();
$progress.show();
$alert.removeClass('alert-success alert-warning');
canvas.toBlob(function (blob) {
var formData = new FormData();
formData.append('avatar', blob, 'avatar.jpg');
$.ajax('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
var percent = '0';
var percentage = '0%';
if (e.lengthComputable) {
percent = Math.round((e.loaded / e.total) * 100);
percentage = percent + '%';
$progressBar.width(percentage).attr('aria-valuenow', percent).text(percentage);
}
};
return xhr;
},
success: function () {
$alert.show().addClass('alert-success').text('Upload success');
},
error: function () {
avatar.src = initialAvatarURL;
$alert.show().addClass('alert-warning').text('Upload error');
},
complete: function () {
$progress.hide();
},
});
});
}
});
});
</script>
</body>
</html>
the cropper script is in: https://fengyuanchen.github.io/cropperjs/js/cropper.js
Using croppiejs helped me solve this issue. To utilize Croppie with a preview, you just set the value of an html image element to croppie's base64 result:
First create croppie instance:
var cropperlg = new Croppie(document.getElementById('croppie-lg'), {
viewport: {
width: 400
height: 800
},
boundary: {
height: 500
width: 1000
}
});
This bit of code binds croppie to an image and executes the crop on click.
EDIT: I simplified the code for a more basic example.
cropperlg.bind({
url: '/images/someimg.jpg'
});
$('#crop-btn').on('click', (e) => {
cropperlg.result({
type: 'canvas',
size: { width: 1000, height: 400 }
}).then(function(result) {
$('#cropped-img').attr('src', result);
})
});
You should be able to figure it out from here.
this worked for me
var cropper = $('#cropper-image').cropper('getCroppedCanvas', {
// Limit max sizes
maxWidth: 4096,
maxHeight: 4096,
});
After setting this, it worked well on both mobile and desktop.

script doesnt allow file name to show in input

Image input is allowing to upload images without displaying the name of the file. I want to be able to see the file name when I upload an image; how can I make this possible? Could it be something to do with my script?
function readURL(input) {
if (input.files && input.files[0]) {
console.log("Reading File.");
var reader = new FileReader();
reader.addEventListener("load", function(e) {
if (jQuery("#preview-gallery li").length == 3) {
input.value = "";
return false;
}
var $imgP = jQuery("<img>", {
class: "uploaded-image icon",
src: reader.result
});
var $item = jQuery("<li>", {
class: "ui-widget-content ui-corner-all hidden"
});
$item.append($imgP).append("<a href='#' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a>");
$item.appendTo(jQuery("#preview-gallery")).show("slow");
makeDrag($item);
updatePreviewCount();
});
if (input.files[0]) {
reader.readAsDataURL(input.files[0]);
} else {
console.log(" Reader: File Not found.");
}
input.value = "";
}
}
function renderContent() {
html2canvas(jQuery("#firstshirt"), {
allowTaint: true,
logging: true
}).then(function(canvas) {
jQuery("#previewImage").append(canvas);
jQuery("#download").css("display", "inline");
jQuery("#download").attr("href", jQuery("#previewImage")[0].children[0].toDataURL());
});
}
function makeDrag(o) {
o.draggable({
helper: "original",
revert: "invalid",
zIndex: 999
});
}
function makeResize(o) {
o.resizable();
}
function addImage($item, $pos) {
console.log(" Fade Item Out");
$item.fadeOut();
var $img = $item.find("img");
$img.css("width", "80px").css("height", "80px");
$item.remove();
updatePreviewCount();
console.log(" Making new Wrap");
var $drop = jQuery("<div>", {
class: "dragbal deleteme",
style: "position: absolute; top: 100px; left: 100px;"
});
$drop.append($img);
console.log($drop);
console.log(" Appending to #boxes");
$drop.appendTo(jQuery("#boxes")).fadeIn();
$drop.draggable({
containment: "#boxes"
});
makeResize($drop.find("img"));
}
function updatePreviewCount() {
var cnt = jQuery("#preview-gallery li").length;
jQuery(".upPreview span").html(cnt + "/3");
}
jQuery(download).ready(function() {
// Setup
jQuery(".file-upload-wrapper").hide();
jQuery(".out-put-img").hide();
jQuery('.smallimages').hide();
makeDrag(jQuery("[id$='-gallery'] ul li"));
jQuery("#boxes").droppable({
accept: ".gallery > li",
drop: function(e, ui) {
console.log("Drop Pos:", ui.offset);
addImage(ui.helper, ui.position);
}
});
// Events
jQuery("#btn-Preview-Image").click(function(e) {
e.preventDefault();
renderContent();
jQuery("#download").removeClass("disabled");
});
jQuery("#download").click(function(e) {
e.preventDefault();
return jQuery(this).hasClass("disabled");
});
jQuery("#imajes45").change(function() {
if (jQuery('#imajes45').val() == "new-upload") {
jQuery(".file-upload-wrapper").show();
jQuery(".file-select").hide();
} else {
jQuery(".file-upload-wrapper").hide();
jQuery(".file-select").show();
}
});
jQuery(".file-select").change(function() {
jQuery(".upPreview").hide();
jQuery("#" + jQuery(this).val() + "-gallery").show();
})
jQuery(".upload-img").change(function() {
readURL(this);
});
});
var myform = document.getElementById('myform');
if (myform != undefined) {
myform.onsubmit = function(e) { /* do some validation on event here */ };
}
$("#wrapper").hover(function() {
$("#boxes").css("border-color", "red");
},
function() {
$("#boxes").css("border-color", "transparent");
});
$(document).ready(function() {
$(".container").on("dblclick", ".deleteme", function() {
console.log('clicked delete')
$(this).remove();
});
<link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"></script> <script src="https://files.codepedia.info/uploads/iScripts/html2canvas.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script> <link rel="stylesheet" href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" /> <script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <link href='https://fonts.googleapis.com/css?family=Philosopher' rel='stylesheet' type='text/css'> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script src="http://circletype.labwire.ca/js/circletype.js"></script><script src="http://tympanus.net/Development/Arctext/js/jquery.arctext.js"></script>
<select id="imajes45">
<option value="">Choose upload</option>
<option value="new-upload">Upload Images</option>
</select>
<div class="file-upload-wrapper" id="draggableHelper" style="display: none;">
<div>
<input type="file" class="upload-img" name="file1" id="file1" onchange="readURL(this);" /><span id='contactus_file1_errorloc' class='error'></span>
</div>
<div>
<input type="file" class="upload-img2" name="file2" id="file2" onchange="readURL(this);" /><span id='contactus_file2_errorloc' class='error'></span>
</div>
<div>
<input type="file" class="upload-img3" name="file4" id="file4" onchange="readURL(this);" /><span id='contactus_file4_errorloc' class='error'></span>
</div>
<div id="upload-preview" class="small upPreview">
<span>0/3</span>
<ul id="preview-gallery" class="gallery ui-helper-reset ui-helper-clearfix">
</ul>
</div>
</div>
here is the prevent default
jQuery("#btn-Preview-Image").click(function(e) {
e.preventDefault();
renderContent();
jQuery("#download").removeClass("disabled");
});
jQuery("#download").click(function(e) {
e.preventDefault();
return jQuery(this).hasClass("disabled");
});

Categories