Trying loading external plugin on click doesn't work - javascript

What I want to achieve is that, when I click on a button, an overlay div containing the Dropzone.js form is created and displayed.
Here's the "normal" script I used before, and everything works fine.
<!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">
<title>Title</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css">
</head>
<body>
<h1>Upload your files</h1>
<form action="uploads" method="post" enctype="multipart/form-data" class="dropzone" id="my-dropzone">
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>
<script>
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: 1, // MB
maxFiles: 1,
acceptedFiles: ".jpg",
dictDefaultMessage: "Either drag your files or click",
addRemoveLinks: true
};
</script>
</body>
</html>
Here's the script that doesn't work:
$(document).ready(function () {
/**
* Promises to load the Dropzone.js files on CDNs
*/
function myAsyncFunction(type, url) {
return new Promise(function (resolve, reject) {
if (type === "js") {
var script = document.createElement("script");
script.src = url;
script.type = "text/javascript";
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
} else if (type === "css") {
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
link.onload = resolve;
link.onerror = reject;
document.head.appendChild(link);
}
})
}
/**
* Overlay div
*/
var uploadDiv = function (__callback) {
var div = document.createElement('div');
div.setAttribute('id', 'dropzone-container');
document.body.appendChild(div);
var h1 = document.createElement('h1');
h1.textContent = "Upload file";
div.appendChild(h1);
var form = document.createElement('form');
form.setAttribute('action', 'uploads');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('class', 'dropzone');
form.setAttribute('id', 'my-dropzone');
div.appendChild(form);
__callback();
};
/**
* Does the job and call the Dropzone object
*/
var upload = function () {
// Get data-options
var options = JSON.parse(this.dataset.options);
// Create HTML
uploadDiv(function () {
myAsyncFunction('css', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css')
.then(
myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js')
.then(
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: options.maxFilesize, // MB
maxFiles: options.maxFiles,
acceptedFiles: options.acceptedFiles,
dictDefaultMessage: "Either drag your files or click",
addRemoveLinks: true
}
)
)
});
}
/**
* Attach EventListener.
* #type {HTMLCollectionOf<Element>}
*/
var btnUpload = document.getElementsByClassName('mb-upload');
for (var i=0; i<btnUpload.length; i++) {
btnUpload[i].addEventListener("click", upload);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!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">
<title>Title</title>
</head>
<body>
<input type="button" class="form-control btn btn-warning mb-upload" data-options='{"maxFilesize":1,"maxFiles":1,"acceptedFiles":".jpeg,.jpg,.png,.gif"}' id="author_avatar" value="Upload...">
</body>
</html>
As you can see, the div is created and the Dropzone.js files are loaded, but the Dropzone form doesn't work as in the previous snippet.
Where am I wrong?

You had a syntax error,
myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js').then(()=>{
//resolve function
})
$(document).ready(function () {
/**
* Promises to load the Dropzone.js files on CDNs
*/
function myAsyncFunction(type, url) {
return new Promise(function (resolve, reject) {
if (type === "js") {
var script = document.createElement("script");
script.src = url;
script.type = "text/javascript";
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
} else if (type === "css") {
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
link.onload = resolve;
link.onerror = reject;
document.head.appendChild(link);
}
})
}
/**
* Overlay div
*/
var uploadDiv = function (__callback) {
var div = document.createElement('div');
div.setAttribute('id', 'dropzone-container');
document.body.appendChild(div);
var h1 = document.createElement('h1');
h1.textContent = "Upload file";
div.appendChild(h1);
var form = document.createElement('form');
form.setAttribute('action', 'uploads');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('class', 'dropzone');
form.setAttribute('id', 'my-dropzone');
div.appendChild(form);
__callback();
};
/**
* Does the job and call the Dropzone object
*/
var upload = function () {
// Get data-options
var options = JSON.parse(this.dataset.options);
// Create HTML
uploadDiv(function () {
myAsyncFunction('css', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css')
.then(
myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js')
.then(()=>{
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: options.maxFilesize, // MB
maxFiles: options.maxFiles,
acceptedFiles: options.acceptedFiles,
dictDefaultMessage: "Either drag your files or click",
addRemoveLinks: true
}
})
)
});
}
/**
* Attach EventListener.
* #type {HTMLCollectionOf<Element>}
*/
var btnUpload = document.getElementsByClassName('mb-upload');
for (var i=0; i<btnUpload.length; i++) {
btnUpload[i].addEventListener("click", upload);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!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">
<title>Title</title>
</head>
<body>
<input type="button" class="form-control btn btn-warning mb-upload" data-options='{"maxFilesize":1,"maxFiles":1,"acceptedFiles":".jpeg,.jpg,.png,.gif"}' id="author_avatar" value="Upload...">
</body>
</html>

Related

.send(formData) Error "GET 404 .../upload.php (Not Found)"

i've found this code on a website for uploading files using javascript, but it doesn't seems to work. Could somebody help me with that please?
Index.php :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div class="row">
<div id="uploads"></div>
<div class="dropzone" id="dropzone">
Drop files fere to upload
</div>
</div>
</div>
<script src="js_script.js" type="text/javascript"></script>
</body>
</html>
And js :
(function() {
var dropzone = document.getElementById('dropzone');
var displayUploads = function(data) {
var uploads = document.getElementById('uploads'),
anchor,
x;
for (x = 0; x < data.length; x = x + 1) {
anchor = document.createElement('a');
anchor.href = data[x].file;
anchor.innerText = data[x].name;
uploads.appendChild(anchor);
}
};
var upload = function(files) {
var formData = new FormData(),
xhr = new XMLHttpRequest(),
x;
for (x = 0; x < files.length; x = x + 1) {
formData.append('file[]', files[x]);
}
xhr.onload = function() {
var data = JSON.parse(this.responseText);
displayUploads(data);
};
xhr.open('post', 'upload.php');
xhr.send(formData);
};
dropzone.ondrop = function(e) {
e.preventDefault();
this.className = 'dropzone';
upload(e.dataTransfer.files);
};
dropzone.ondragover = function() {
this.className = 'dropzone dragover';
return false;
};
dropzone.ondragleave = function() {
this.className = 'dropzone';
return false;
};
}());
and upload.php :
<?php
header("Content-Type: application/json");
$uploaded = array();
if(!empty($_FILES['file']['name'][0])){
foreach($_FILES['file']['name'] as $position => $name){
if(move_uploaded_file($_FILES['file']['tmp_name'][$position], 'uploads/'.$name)){
$uploaded[] = array(
'name' => $name,
'file' => 'uploads/'.$name
);
}
}
}
echo json_encode($uploaded);
?>
And now this issue :
GET .../upload.php 404 (Not Found)
and related code to issue :
xhr.send(formData);
btw what is that "GET" showing in console??
I just saved the file "Upload.php" with uppercase "U" which should be "upload.php".

Call JavaScript via Java

Initial situation :
I have a JavaFX program where I put data into a MYSQL database, enter and save it.
In the JavaFX program, I have a PDF displayed via WebView using JavaScript. From the JavaFX programm i call the html to open the WebView
Problem:
If I display different data records, the respective PDF should be displayed.
Question:
How do I hand over the file path from JavaFX to JavaScript.
JavaFX Code to show the PDF
public void handleShowPDF(ActionEvent actionEvent) throws MalformedURLException {
try {
eWebView.setVisible(true);
webEngine = eWebView.getEngine();
webEngine.setJavaScriptEnabled(true);
URL url = this.getClass().getResource("/jScript/index.html");
webEngine.load(url.toString());
}
catch (Exception ex) {
System.err.print("error " + ex.getMessage());
ex.printStackTrace();
}
HTML Code for calling JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.7.2/css/all.css"
integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="style.css" />
<title>PDF Viewer</title>
</head>
<body>
<div class="top-bar">
<button class="btn" id="prev-page">
<i class="fas fa-arrow-circle-left"></i> Prev Page
</button>
<button class="btn" id="next-page">
Next Page <i class="fas fa-arrow-circle-right"></i>
</button>
<span class="page-info">
Page <span id="page-num"></span> of <span id="page-count"></span>
</span>
</div>
<canvas id="pdf-render"></canvas>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<script src="main.js"></script>
</body>
</html>
JavaScript Code
// How do I get the path value from JavaFX
const url = '../docs/pdf.pdf';
let pdfDoc = null,
pageNum = 1,
pageIsRendering = false,
pageNumIsPending = null;
const scale = 1.5,
canvas = document.querySelector('#pdf-render'),
ctx = canvas.getContext('2d');
// Render the page
const renderPage = num => {
pageIsRendering = true;
// Get page
pdfDoc.getPage(num).then(page => {
// Set scale
const viewport = page.getViewport({ scale });
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderCtx = {
canvasContext: ctx,
viewport
};
page.render(renderCtx).promise.then(() => {
pageIsRendering = false;
if (pageNumIsPending !== null) {
renderPage(pageNumIsPending);
pageNumIsPending = null;
}
});
// Output current page
document.querySelector('#page-num').textContent = num;
});
};
// Check for pages rendering
const queueRenderPage = num => {
if (pageIsRendering) {
pageNumIsPending = num;
} else {
renderPage(num);
}
};
// Show Prev Page
const showPrevPage = () => {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
};
// Show Next Page
const showNextPage = () => {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
};
// Get Document
pdfjsLib
.getDocument(url)
.promise.then(pdfDoc_ => {
pdfDoc = pdfDoc_;
console.log(pdfDoc);
document.querySelector('#page-count').textContent = pdfDoc.numPages;
renderPage(pageNum);
})
.catch(err => {
// Display error
const div = document.createElement('div');
div.className = 'error';
div.appendChild(document.createTextNode(err.message));
document.querySelector('body').insertBefore(div, canvas);
// Remove top bar
document.querySelector('.top-bar').style.display = 'none';
});
// Button Events
document.querySelector('#prev-page').addEventListener('click', showPrevPage);
document.querySelector('#next-page').addEventListener('click', showNextPage);

How do I upload video to server after previewed using phonegap

Pls I urge for assistance on how to upload video captured with phonegap android app. I could upload captured video, but I want the user of the app to watch the captured video before uploading it. That is where I'm having problem.
The code I am using is below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/jquery.mobile-1.2.0.min.css" />
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/jquery.mobile-1.2.0.min.js"></script>
<script src="js/modernizr-latest.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", init, false);
function init() {
document.querySelector("#takeVideo").addEventListener("touchend", function() {
alert("Take video");
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 1, duration: 10});
}, false);
}
function captureError(e) {
console.log("capture error: "+JSON.stringify(e));
}
function captureSuccess(s) {
console.log("Success");
console.dir(s[0]);
var v = "<video controls='controls'>";
v += "<source src='" + s[0].fullPath + "' type='video/mp4'>";
v += "</video>";
document.querySelector("#videoArea").innerHTML = v;
}
function uploadFile(s) {
// Get URI of picture to upload
var img = document.getElementById('videoArea');
var mediaFile = img;
alert(mediaFile);
if (!mediaFile || (img.style.display == "none")) {
alert("Take picture or select picture from library first.");
return;
}
var ft = new FileTransfer(),
path = mediaFile.substr(mediaFile.lastIndexOf('/')+1),
name = mediaFile.name;
var options = new FileUploadOptions();
options.mimeType = "document";
options.fileName = name;
options.chunkedMode = true;
options.params = params;
ft.upload(path,
"http://www.example.com/folder/upload.php",
function(result) {
alert('Upload success: ' + result.responseCode);
alert(result.bytesSent + ' bytes sent');
},
function(error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
options);
}
</script>
</head>
<body>
<button id="takeVideo">Take Video</button><br>
<b>Status:</b> <span id="camera_status"></span><br>
<div id="videoArea"></div>
<button type="submit" onclick="uploadFile();">Submit</button>
</body>
</html>
Pls I count on your assistance to solve this challenge. I do not know how to reference "video" tagname nor extract image path from the videoArea id of the div.

When using XLSX to parse excelsheet - it is throwing _fs is undefined

I am trying to use the XLSX library to read data from excelsheet but I am getting this:-
ERROR: _fs is undefined at xlsx.js (line 11388, col 59)
Here is my code :-
<html>
<head>
<title>Read Excel</title>
<meta meta http-equiv="Content-Type" content="text/html;" charset="UTF-8"/>
</head>
<body>
<script src="xlsx.js"></script>
<script>
function actionbegins(){
console.log("Inside the function action begins !!");
if(typeof XLSX === 'undefined' && typeof require !== 'undefined')
XLSX = require('xlsx');
var workbook = XLSX.readFile("Invoice.xlsx", {type: 'base64'});
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = 'A2';
var worksheet = workbook.Sheets[first_sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = desired_cell.v;
console.log("we got the value as --> "+desired_value);
}
</script>
<button id="btnDoIt" onclick="actionbegins()" name="btnDoIt" class="btn btn-primary">do It !!</button>
</body>
</html>
I tried searching the net for a suitable answer but could not find any. Please suggest.
It was not working because the file wasn't loaded completely and it started processing it.
Here is the code that is working absolutely fine :
<html>
<head>
<title>Read Excel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script lang="javascript" src="dist/xlsx.core.min.js"></script>
</head>
<body>
<script>
function letsdoit(){
var url = "Invoice.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = 'A1';
var worksheet = workbook.Sheets[first_sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = desired_cell.v;
alert("value is -- "+desired_value);
}
oReq.send();
}
</script>
<input type="file" name="file" id="selectfile" onchange="letsdoit()" />
</body>
</html>

not always same result with fileReader Javascript

I am using fileReader for checking if a profile picture uploaded matches with my conditions. However, i don't have always the same result. Can you help me to fix that bug ?
Here my htlm code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File API</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">
<h1>Image File Reader</h1>
<div>
Select an image file:
<input type="file" id="fileInput">
</div>
</div>
<script src="images.js"></script>
</body>
</html>
Here my javascript/fileReader (images.js) code:
window.onload = function()
{
var width=0;
var height=0;
var exten= false;
var size = false;
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e)
{
var file = fileInput.files[0];
var imageType = /image.png/;
if (file.type.match(imageType))
{
exten = true;
var reader = new FileReader();
reader.onload = function(e)
{
var img = new Image();
img.src = reader.result;
img.onload = function()
{
width=this.width;
height=this.height;
}
}
reader.readAsDataURL(file);
}
else
{
exten= false;
}
if(width == 50 && height ==50)
{
size = true;
}
else
{
size = false;
}
//Here, we check that the image matches with png and 50*50px
if(size && exten)
{
alert('Your image is ok.');
}
else
{
if(!size && !exten)
{
alert('Image needs to be 50*50px and in png');
}
else
{
if(!size && exten)
{
alert('Image needs to be 50*50px');
}
else
{
if(size && !exten)
{
alert('Image needs to be in png');
}
}
}
}
});
}
Thank you for your help
You've to wait the execution of the img.onload event before checking width and height.
The code that's outside that event handler and that uses those properties should be moved inside it.

Categories