Progress bar for the form - javascript

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>

Related

How to allow user to change font size

I am making a google docs like app, and I want the user to be able to select the text, and then change the size to whatever they want. I tried to use variables but it didn't work so I am not sure what to do. Is there any way to allow the user to change the font size and if so how?
Here is the code for the app:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Editor</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<button class="bold" onclick="document.execCommand('bold',false,null);">
𝗕
</button>
<button class="italic" onclick="document.execCommand('italic',false,null);">
𝘐
</button>
<button
class="underline"
onclick="document.execCommand('underline',false,null);"
>
U̲
</button>
<input
type="color"
class="color-picker"
id="colorPicker"
oninput="changeColorText(this.value);"
/>
<label>Select color</label>
<button id="highlight"><mark>Highlight</mark></button>
<fieldset class="userInput" contenteditable="true"></fieldset>
<script>
var boldBtn = document.querySelector(".bold");
var italicBtn = document.querySelector(".italic");
var underlineBtn = document.querySelector(".underline");
var colorPicker = document.querySelector(".color-picker");
var highlightBtn = document.querySelector("#highlight");
boldBtn.addEventListener("click", function () {
boldBtn.classList.toggle("inUse");
});
italicBtn.addEventListener("click", function () {
italicBtn.classList.toggle("inUse");
});
underlineBtn.addEventListener("click", function () {
underlineBtn.classList.toggle("inUse");
});
highlightBtn.addEventListener("click", function () {
highlightBtn.classList.toggle("inUse");
});
const changeColorText = (color) => {
document.execCommand("styleWithCSS", false, true);
document.execCommand("foreColor", false, color);
};
document
.getElementById("highlight")
.addEventListener("click", function () {
var range = window.getSelection().getRangeAt(0),
span = document.createElement("span");
span.className = "highlight";
span.appendChild(range.extractContents());
range.insertNode(span);
});
</script>
</body>
</html>
I think this is the output you want. Also, don't use document.execCommand, it has been deprecated
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Editor</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<button class="bold" onclick="document.execCommand('bold',false,null);">
𝗕
</button>
<button class="italic" onclick="document.execCommand('italic',false,null);">
𝘐
</button>
<button
class="underline"
onclick="document.execCommand('underline',false,null);"
>
U̲
</button>
<input
type="color"
class="color-picker"
id="colorPicker"
oninput="changeColorText(this.value);"
/>
<label>Select color</label>
<button id="highlight"><mark>Highlight</mark></button>
<input
type="number"
class="font-size"
id="fontSize"
/>
<label>Select Font Size</label>
<fieldset class="userInput" contenteditable="true"></fieldset>
<script>
var boldBtn = document.querySelector(".bold");
var italicBtn = document.querySelector(".italic");
var underlineBtn = document.querySelector(".underline");
var colorPicker = document.querySelector(".color-picker");
var fontSize = document.querySelector("#fontSize");
var highlightBtn = document.querySelector("#highlight");
var userInput = document.querySelector('.userInput');
boldBtn.addEventListener("click", function () {
boldBtn.classList.toggle("inUse");
});
italicBtn.addEventListener("click", function () {
italicBtn.classList.toggle("inUse");
});
underlineBtn.addEventListener("click", function () {
underlineBtn.classList.toggle("inUse");
});
highlightBtn.addEventListener("click", function () {
highlightBtn.classList.toggle("inUse");
});
const changeColorText = (color) => {
document.execCommand("styleWithCSS", false, true);
document.execCommand("foreColor", false, color);
};
fontSize.addEventListener('input', updateValue);
function updateValue(e) {
userInput.style.fontSize = `${e.target.value}px`;
}
document
.getElementById("highlight")
.addEventListener("click", function () {
var range = window.getSelection().getRangeAt(0),
span = document.createElement("span");
span.className = "highlight";
span.appendChild(range.extractContents());
range.insertNode(span);
});
</script>
</body>
</html>
Add this to your HTML:
<button class="font-smaller">-</button>
<button class="font-bigger">+</button>
Add this to your JS:
const fontSmaller = document.querySelector(".font-smaller");
const fontBigger = document.querySelector(".font-bigger");
let fontSize = 15.5; // play with this number if needed
fontSmaller.addEventListener("click", () => {
document.querySelector(".userInput").style.fontSize = `${fontSize--}px`;
});
fontBigger.addEventListener("click", () => {
document.querySelector(".userInput").style.fontSize = `${fontSize++}px`;
});
Change as needed. This will change the size of the whole text.
You can implement it like this.
// Increase/descrease font size
$('#increasetext').click(function() {
curSize = parseInt($('#content').css('font-size')) + 2;
if (curSize <= 32)
$('#content').css('font-size', curSize);
});
$('#resettext').click(function() {
if (curSize != 18)
$('#content').css('font-size', 18);
});
$('#decreasetext').click(function() {
curSize = parseInt($('#content').css('font-size')) - 2;
if (curSize >= 14)
$('#content').css('font-size', curSize);
});
header {
text-align: center;
}
/* text-controls */
button {
vertical-align: bottom;
margin: 0 0.3125em;
padding: 0 0.3125em;
border: 1px solid #000;
background-color: #fff;
font-weight: bold;
}
button#increasetext {
font-size: 1.50em;
}
button#resettext {
font-size: 1.25em;
}
button#decreasetext {
font-size: 1.125em;
}
.textcontrols {
padding: 0.625em 0;
background: #ccc;
}
/* content */
#content {
margin: 3em 0;
text-align: left;
}
/* demo container */
#container {
width: 90%;
margin: 0 auto;
padding: 2%;
}
#description {
margin-bottom: 1.25em;
text-align: left;
}
#media all and (min-width: 700px) {
#container {
width: 700px;
}
button {
margin: 0 0.625em;
padding: 0 0.625em;
}
}
<div id="container">
<header>
<h1 id="title">
Allow Users to Change Font Size
</h1>
<p>Click the buttons to see it in action</p>
<div class="textcontrols">
<button role="button" id="decreasetext" <span>smaller</span>
</button>
<button role="button" id="resettext">
<span>normal</span>
</button>
<button role="button" id="increasetext">
<span>bigger</span>
</button>
</div>
<!--/.textcontrols-->
</header>
<main id="content" role="main">
<div id="description">
<h2>Allow users to resize text on the page via button controls.</h2>
<p>In this instance, users can decrease text, increase text, or reset it back to normal.</p>
<h2>Set default text size with CSS</h2>
<p>The default text size must be set using an internal stylesheet in the header of your page. In this case: <code>font-size: 1.125em</code> (aka, 18px).</p>
<h2>Set the controls with JavaScript</h2>
<p>Then we set the resize controls with JavaScript. In this example, we're resizing all text within the div with an id of "content".</p>
<p>The controls check the current text size, and then changes it (or not) accordingly.</p>
</div>
<!--/#description-->
</main>
<!--/#content-->
</div>
<!--/#container-->

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');

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.

Changing Iframes HTML

I need a script to change the iframes src every certain amount of seconds. The time between the change is different between each one.
Example:
Page Loads
Google.com is loaded.
15 seconds later
Yahoo.com is loaded.
37 seconds later
Ask.com is loaded.
12 seconds later
Dogpile.com is loaded.
and so on and so forth.
I've tried that:
<html>
<head>
<meta charset="utf-8" />
<title>Monitor Presidência</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.js"></script>
</head>
<body>
<div style="width: 100%; display: flex;">
<div class="ui teal progress" data-percent="0" id="example1" style="width: 90%;margin-bottom: 0px">
<div class="bar"></div>
</div>
<div class="ui icon buttons" style="width: 10%">
<button class="ui button" style="width: 25%" onclick="menos_um()">
<i class="left chevron icon"></i>
</button>
<button class="ui button " style="width: 25%" onclick="inicia()">
<i class="play icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="para_aplicacao()">
<i class="pause icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="mais_um()">
<i class="right chevron icon"></i>
</button>
</div>
</div>
<iframe id="envase" class="frame_mon" style="width: 100%;height: 100%;" src="www.google.com.br"></iframe>
<iframe id="frete_hl" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.yahoo.com.br"></iframe>
<iframe id="frete_hl_acum" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.terra.com.br"></iframe>
</body>
<script>
var arr_monitores = ["envase", "frete_hl", "frete_hl_acum"];
var num_monitor = 0;
var progresso = 0;
var myVar;
var setintervalatualizaframe;
function mais_um() {
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";*/
progresso = 100;
myStopFunction();
inicia();
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}*/
};
function menos_um() {
//progresso = 100;
if (num_monitor === 0) {
num_monitor = 2;
} else {
num_monitor--;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";
progresso = 0;
myStopFunction();
inicia();
};
function inicia() {
clearInterval(setintervalatualizaframe);
myStopFunction();
myVar = setInterval(function () {
if (progresso === 100) {
progresso = 0;
if (num_monitor === 2) {
location.reload();
//num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none')
document.getElementById(arr_monitores[num_monitor]).style.display = "";
};
progresso++;
progresso++;
$('#example1').data('percent', progresso);
$('#example1').progress();
}, 3800);
}
function myStopFunction() {
clearInterval(myVar);
//atualiza_frame();
}
inicia();
function para_aplicacao(){
clearInterval(myVar);
atualiza_frame();
}
function atualiza_frame() {
clearInterval(setintervalatualizaframe);
setintervalatualizaframe = setInterval(function () {
document.getElementById(arr_monitores[num_monitor]).src=document.getElementById(arr_monitores[num_monitor]).src;
},1);
}
</script>
</html>
The way you are using setInterval and setTimeout is not properly
handled, as it creates a timer id to schedule execution. 0
A much more efficient way is to use the Promises async library, which is displayed below. 1
For websites that won't work, they are using a response header that won't allow their pages to be framed. You can work around this with some back-end program, where the server loads the web files then forwards them. 2
<!DOCTYPE html>
<html>
<head>
<title> Hello </title>
<style>
iframe {
display: block;
width: 1000px;
height: 500px;
margin-left: auto;
margin-right: auto;
}
iframe:focus {
outline: none;
}
button {
display: block;
margin: auto auto;
}
label {
display: block;
margin-left: auto;
margin-right: auto;
}
input {
display: block;
margin: auto auto;
}
</style>
</head>
<body>
<div id='main'>
<button id='wait' onclick='wait()'>Wait</button>
<label>Seconds</label>
<input type='number' id='seconds' placeholder='milliseconds'>
<button id='switching' onclick='webSwitch()'>Switch sites</button>
<iframe id='switchMe' src='https://codepen.io'></iframe>
</div>
<script>
//Array of webpages
var webList = ["https://www.bing.com", "https://www.walmart.com","https://www.codepen.io"];
//For tracking position in array
var count = 0;
//Function to be ran by event
function webSwitch() {
console.log('I have been called');
if (count >= webList.length) {
count = 0;
}
//Setting new URL
document.getElementById('switchMe').src = webList[count];
//Make sure to use next URL
count++;
}
function wait() {
console.log('Click!');
var numMS = document.getElementById('seconds').value;
sleep(numMS).then(() => {
webSwitch();
})
}
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
</script>
</body>
</html>

how to convert image into byte array in jsp/javascript

hi i am acquiring the image from the scanner device successfully i want to store that image in data base i am thinking that i need to convert into byte array then pass to controller but i am not able to convert that image into byte array.
can any one please suggest me that is it right approach or not,if it is wrong then what is the alternate way please help me.
this is my code.
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<title>Scanning documets</title>
<script type="text/javascript"
src="http://direct.asprise.com/scan/javascript/base/scanner.js"></script>
<!-- required for scanning -->
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- optional -->
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css"
rel="stylesheet">
<!-- optional -->
<style type="text/css">
img.zoom {
margin-right: 4px;
}
body {
margin: 20px 10px;
}
</style>
<script>
// -------------- Optional status display, depending on JQuery --------------
function displayStatus(loading, mesg, clear) {
$('#info').empty(); // jQuery is used
if (loading) {
$('#info')
.html(
(clear ? '' : $('#info').html())
+ '<p><img src="http://asprise.com/legacy/product/_jia/applet/loading.gif" style="vertical-align: middle;" hspace="8"> '
+ mesg + '</p>');
} else {
$('#info').html((clear ? '' : $('#info').html()) + mesg);
}
}
// -------------- scanning related code: independent of any 3rd JavaScript library --------------
/* function scanSimple() {
displayStatus(true, 'Scanning', true);
com_asprise_scan_request(myCallBackFunc,
com_asprise_scan_cmd_method_SIMPLE_SCAN, // simple scan without the applet UI
com_asprise_scan_cmd_return_IMAGES_AND_THUMBNAILS,
null);
}
*/
function scan() {
displayStatus(true, 'Scanning', true);
com_asprise_scan_request(myCallBackFunc,
com_asprise_scan_cmd_method_SCAN, // normal scan with the applet UI
com_asprise_scan_cmd_return_IMAGES_AND_THUMBNAILS, {
'wia-version' : 2
});
}
/* function scanThenUpload() {
displayStatus(true, 'Scanning', true);
com_asprise_scan_request(myCallBackFunc,
com_asprise_scan_cmd_method_SCAN_THEN_UPLOAD, // scan and then upload directly in the applet UI
com_asprise_scan_cmd_return_IMAGES_AND_THUMBNAILS,
{
'upload-url': 'http://asprise.com/scan/applet/upload.php?action=upload' // target URL
,'format': 'PDF'
});
} */
/** Use this callback function to get notified about the scan result. */
function myCallBackFunc(success, mesg, thumbs, images) {
var logText;
displayStatus(false, '', true);
logText = 'Callback function invoked: success = ' + success
+ ", mesg = " + mesg;
logText += '\nThumbs: ' + (thumbs instanceof Array ? thumbs.length : 0)
+ ", images: " + (images instanceof Array ? images.length : 0)
+ ",image name" + (images instanceof Array ? images.name : 0);
logToConsole(logText, !(success || mesg == 'User cancelled.'));
displayStatus(false, '<pre>' + logText + '</pre>', true);
for (var i = 0; (images instanceof Array) && i < images.length; i++) {
addImage(images[i], document.getElementById('images'));
}
}
/** We use this to track all the images scanned so far. */
var imagesScanned = [];
function addImage(imgObj, domParent) {
imagesScanned.push(imgObj);
var imgSrc = imgObj.datatype == com_asprise_scan_datatype_BASE64 ? 'data:'
+ imgObj.mimetype + ';base64,' + imgObj.data
: imgObj.data;
var elementImg = createDomElementFromModel({
'name' : 'img',
'attributes' : {
'src' : imgSrc,
'height' : '100',
'class' : 'zoom'
}
});
$('<input>').attr({
type : 'hidden',
name : '',
})
$('#imageData').val(imgSrc);
domParent.appendChild(elementImg);
// optional UI effect that allows the user to click the image to zoom.
enableZoom();
}
function submitForm1() {
displayStatus(true, "Submitting in progress, please standby ...", true);
com_asprise_scan_submit_form_with_images('form1', imagesScanned,
function(xhr) {
alert("image :" + imagesScanned);
if (xhr.readyState == 4) { // 4: request finished and response is ready
displayStatus(false,
"<h2>Response from the server: </h2>"
+ xhr.responseText, true);
alert("before");
document.getElementById("form1").submit();
}
});
}
</script>
</head>
<body style="margin: 10px 30px;">
<div
style="display: block; position: absolute; right: 30px; top: 20px;">
<!-- <a href="http://asprise.com/" target=_blank> <img src="http://asprise.com/res/img/nav/logo.fw.png"/> </a> -->
</div>
<h2></h2>
<!-- <p style="color: #9eadc0;">For evaluation purpose only. Please order a license from <a href="http://asprise.com/" target=_blank>asprise.com</a>
| View source code of this page
</p> -->
<div class="panel panel-info" style="margin: 20px 0px;">
<div class="panel-heading">
<h3 class="panel-title">Scann your docs:</h3>
</div>
<div class="panel-body">
<form id="form1" action="<c:url value='/upload'/>" method="POST"
enctype="multipart/form-data" target="_blank">
<!-- <label for="field1"
style="display: inline-block; width: 150px; text-align: right;">Field
1</label> <input id="field1" name="field1" type="text" value="value 1" /> <input
type="file" name="file" /> <br> -->
<span style="height: 4px;"></span><br> <label
style="display: inline-block; width: 150px; text-align: right;">Documents</label>
<button type="button" class="btn btn-info" onclick="scan();">Scan</button>
<!-- <button type="button" class="btn btn-default" onclick="scanSimple();">Simple Scan</button>
<button type="button" class="btn btn-default" onclick="scanThenUpload();">Scan Then Upload</button> -->
<div id="images" style="margin-left: 154px; margin-top: 10px;">
<input type="hidden" name="imageName" value="" />
</div>
<input type="button" class="btn btn-primary" value="Submit form"
onclick="submitForm1();"
style="margin-left: 154px; margin-top: 20px;">
</form>
</div>
</div>
<div id="info" class="well"
style="display: block; background-color: #fff; height: 500px; margin-top: 12px; padding: 12px; overflow: scroll;">
<p>
<i>Information window</i>
</p>
</div>
<script src="http://yyx990803.github.io/zoomerang/zoomerang.js"></script>
<script>
function enableZoom() {
Zoomerang.config({
maxWidth : window.innerWidth, // 400,
maxHeight : window.innerHeight, // 400,
bgColor : '#000',
bgOpacity : .85
}).listen('.zoom');
}
</script>
</body>
</html>
You can get the image binary in BASE64 format. The imgObj.data in below code is the BASE64 format of image object:
function addImage(imgObj, domParent) {
imagesScanned.push(imgObj);
var imgSrc = imgObj.datatype == com_asprise_scan_datatype_BASE64 ? 'data:'
+ imgObj.mimetype + ';base64,' + imgObj.data
: imgObj.data;
...
To get the actual binary bytes, you can use:
var bin = window.atob(imgObj.data)
For a complete discussion of converting BASE64 to binary, please refer to: Base64 encoding and decoding in client-side Javascript
For a complete usage of scanner.js, you may consult Developer guide to scanner.js: cross-Browser HTML/JavaScript Scanning - Acquires images from scanners to web pages (Java, C# ASP.NET, PHP)

Categories