How to validate image size before upload? - javascript

I use valums file uploader and I have a problem with image dimension validatation before upload. image_extension and image_filesize return false, but because image dimnension is in onload async function, returning false has no effect and image is submitted and uploaded.
sample code:
function create_uploader()
{
var uploader = new qq.FileUploaderBasic(
{
button: $('#upload_button')[0],
action: 'mdl/sys.upload.img.php',
maxConnections: 7,
debug: false,
multiple: false,
params:
{
upload_dir: '../files/_temp/',
image_size: '1280,1024',
thumb_size: '240,240'
},
onSubmit: function(id, fileName)
{
// validate extension
var file_extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName):undefined;
if (!(file_extension && /^(jpg|JPG|jpeg|JPEG|png|PNG)$/.test(file_extension)))
{
return false;
// OK, execution stop
}
// validate image size
var img_filesize = window.event.target.files[0].size;
if (img_filesize > 1048576)
{
return false;
// OK, execution stop
}
// validate image dimension
var img_size = new Image();
img_size.src = window.URL.createObjectURL(window.event.target.files[0]);
img_size.onload = function()
{
var img_width = img_size.naturalWidth;
var img_height = img_size.naturalHeight;
window.URL.revokeObjectURL(img_size.src);
if (img_width < 640 || img_width > 800)
{
return false;
}
if (img_height < 480 || img_height > 600)
{
return false;
}
}
},
onProgress: function(id, fileName, loaded, total)
{
// progress code
},
onComplete: function(id, fileName, results)
{
// complete code
}
});
}
create_uploader();
Any ideas how to do this?
Edit: Subquestion.
How i can call in onSubmit procedure cancel and dequeue event which valums file uploader handling? If is this possible, then i can call this events in my validation and cancel upload image..

I have solution :)
This is not entirely the whole code because it is a bit complicated. It works something like this to me:
sys.upload.php
<script type="text/javascript">
$(document).ready(function()
{
function create_uploader()
{
var internal_counter = 0; // very important for multiple upload!
var uploader = new qq.FileUploaderBasic(
{
button: $('#upload_button')[0],
action: 'mdl/sys.upload.img.php',
maxConnections: 5,
multiple: true,
debug: false,
params:
{
upload_dir: '../files/_temp/',
image_size: '1280,1024',
thumb_size: '<?php echo isset ($thumb_size) ? $thumb_size : '240,240'; ?>'
},
onSubmit: function(id, fileName)
{
// reset internal counter only if submit form button is enabled
if ($('#submit_form').prop('disabled') == false)
{
internal_counter = 0;
}
// find upload button and temperatory disable it
setTimeout(function(){$('#upload_button').css({'opacity': '0.25'}).find("input[type='file']").css({'cursor': 'default'}).prop('disabled', true)},25);
// disable submit form button
$('#submit_form').prop('disabled', true);
// create new form data
var image_data_temp = null;
var form_data = new FormData();
form_data.append('file', $("input[type='file']")[0].files[internal_counter]);
form_data.append('filesize', '5242880');
form_data.append('min_width', '600');
form_data.append('max_width', '4096');
form_data.append('min_height', '450');
form_data.append('max_height', '2160');
// send new form for validate
$.ajax(
{
type: 'POST',
url: 'mdl/sys.upload-validate.php',
async: false,
data: form_data,
cache: false,
contentType: false,
processData: false
}).done(function(results)
{
image_data_temp = results;
});
var image_data = image_data_temp.split(';');
/*
image_data[0] => status message
image_data[1] => name
image_data[2] => type
image_data[3] => size
image_data[4] => human size
image_data[5] => width
image_data[6] => height
image_data[7] => icon symbol shortcut
*/
// counter must increase before check validation
internal_counter ++;
if (image_data[0] != 'ok')
{
// stop if validation is not OK
// you can here add some function for error etc.
console.log (image_data[0]);
// enable submit form button
$('#submit_form').prop('disabled', false);
// enable upload button
setTimeout(function(){$('#upload_button').css({'opacity': '1'}).find("input[type='file']").css({'cursor': 'pointer'}).prop('disabled', false);},25);
return false;
}
// validation is ok now, onProgress is processed
},
onProgress: function(id, fileName, loaded, total)
{
// on progress code
},
onComplete: function(id, fileName, results)
{
// process if is image uploaded
internal_counter = 0;
// enable submit form button
$('#submit_form').prop('disabled', false);
// enable upload button
$('#upload_button').css({'opacity': '1'}).find("input[type='file']").css({'cursor': 'pointer'}).prop('disabled', false);
}
});
}
create_uploader();
});
</script>
sys.upload-validate.php
<?php
header ('Connection: close');
require_once '../sys.functions.php'; // it is not necessary
function show_data($str_a, $str_b, $str_c, $str_d, $str_e, $str_f, $str_g, $str_h)
{
echo $str_a;
echo ';';
echo $str_b;
echo ';';
echo $str_c;
echo ';';
echo $str_d;
echo ';';
echo $str_e;
echo ';';
echo $str_f;
echo ';';
echo $str_g;
echo ';';
echo $str_h;
}
$image_info = getimagesize ($_FILES['file']['tmp_name']);
$image_width = $image_info[0];
$image_height = $image_info[1];
if
(
$_FILES['file']['type'] != 'image/pjpeg' &&
$_FILES['file']['type'] != 'image/jpeg' &&
$_FILES['file']['type'] != 'image/x-png' &&
$_FILES['file']['type'] != 'image/png'
)
{
show_data
(
'Nesprávny typ súboru. Podporované sú iba JPG a PNG obrázky.',
$_FILES['file']['name'],
$_FILES['file']['type'],
$_FILES['file']['size'],
human_file_size($_FILES['file']['size']),
$image_width,
$image_height,
'file'
);
return;
}
if ($_FILES['file']['size'] > (int)$_POST['filesize'])
{
show_data
(
'Súbor je príliš veľký (' . human_file_size($_FILES['file']['size']) . '). Maximálna povolená veľkosť pre súbor je ' . human_file_size((int)$_POST['filesize']) . '.',
$_FILES['file']['name'],
$_FILES['file']['type'],
$_FILES['file']['size'],
human_file_size($_FILES['file']['size']),
$image_width,
$image_height,
'file'
);
return;
}
if ($image_width < (int)$_POST['min_width'] || $image_width > (int)$_POST['max_width'])
{
show_data
(
'Nesprávna šírka (' . $image_width . ' bodov). Minimálna šírka musí byť ' . $_POST['min_width'] . ', maximálna ' . $_POST['max_width'] . ' bodov.',
$_FILES['file']['name'],
$_FILES['file']['type'],
$_FILES['file']['size'],
human_file_size($_FILES['file']['size']),
$image_width,
$image_height,
'wdt'
);
return;
}
if ($image_height < (int)$_POST['min_height'] || $image_height > (int)$_POST['max_height'])
{
show_data
(
'Nesprávna výška (' . $image_height . ' bodov). Minimálna výška musí byť ' . $_POST['min_height'] . ', maximálna ' . $_POST['max_height'] . ' bodov.',
$_FILES['file']['name'],
$_FILES['file']['type'],
$_FILES['file']['size'],
human_file_size($_FILES['file']['size']),
$image_width,
$image_height,
'hgh'
);
return;
}
show_data
(
'ok',
$_FILES['file']['name'],
$_FILES['file']['type'],
$_FILES['file']['size'],
human_file_size($_FILES['file']['size']),
$image_width,
$image_height,
null
);
return;
?>
Maybe it helps someone :)

Related

close current popup upon file download dialog is shown

I have tried to search the solution but could not get any relevant answer. I want to close the current popup once File download popup opens in the browser. For example, in the source code below if i write "window.close()" after ajax request then file download popup is never shown.
But once i remove this line then file download works but how would i close the current popup?
My use case is:
main.php
<script>
window.open('popup.php','redirect','width=500,height=500');
</script>
popup.php
<body>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script>
var url = 'download.php';
var output_type = 'xls';
params = "function=execute_cache&output="+output_type;
$.ajax({
type: "POST",
url: url,
data: params,
success: function(response, status, request) {
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1) {
var form = $('<form method="POST" action="' + url + '">');
$.each(params, function(k, v) {
form.append($('<input type="hidden" name="' + k +
'" value="' + v + '">'));
});
$('body').append(form);
form.submit();
}
}
});
window.close();
</script>
</body>
download.php
<?php
$handle = fopen("file.txt", "w");
fwrite($handle, "text1.....");
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
Note: I can not use setTimeout function to auto close popup because i do not know in how much time file will be downloaded. So i can not give a maximum time. The code shown in download.php is not an actual code. Actually, i would fetch huge data and generate XLS.
I just want to get current popup closed automatically as soon as File download popup is shown to user to download the file.
use promise to do such async calls. learn more about it https://www.sitepoint.com/overview-javascript-promises/
also give a id to window.open like
windowPopup = window.open('popup.php','redirect','width=500,height=500');
and use
windowPopup.close();
var windowPopup = window.open('popup.php','redirect','width=500,height=500');
function callRequest () {
return new Promise(function (resolve, reject) {
var url = 'download.php';
var output_type = 'xls';
var params = "function=execute_cache&output="+output_type;
var xhr = new XMLHttpRequest();
xhr.open('POST', url, param);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1) {
var form = $('<form method="POST" action="' + url + '">');
$.each(params, function(k, v) {
form.append($('<input type="hidden" name="' + k +
'" value="' + v + '">'));
});
$('body').append(form);
setTimeout(function(){
form.submit();
resolve(true);
}, 1000);
}
} else {
reject(false);
}
};
xhr.onerror = function () {
reject(false);
};
xhr.send();
});
}
callRequest()
.then(function (res) {
console.log('result : ', res);
if(res) {
windowPopup.close();
}
})
.catch(function (err) {
console.error('error : ', err);
});

Ajax url contain data

I want design a login form via PHP + JQuery Ajax.
I have 2 textbox :
txtbox1 id="kadiID"
txtbox2 id="sifreID"
and button :
id="btnGiris"
My buttons JQuery code is:
$('#btnGiris').on("click", function(){
var kullaniciID=$("#kadiID").val();
var sifreID=$("#sifreID").val();
var cpthcID='';
if($('#kontrolID').length){
cpthcID=$('#kontrolID').val();
alert("cpthc: [" + cpthcID + "]");
}
$.ajax({
type : "GET",
url :'giris.php',
data:({ kadi : kullaniciID, sifre : sifreID, cpthc : cpthcID }),
cache:false,
beforeSend :function()
{
// other codes
},
success :function(donen_veri){
alert(donen_veri);
},
complete:function()
{
// other code
},
})
return false;
})
When I click button, my send datas from javascript are not process in giris.php file. Also I opened development tool via F12 and open network tab then I click button I saw a url like this:
Datas which I send via ajax data field are apear in url:
How can I solve this.
I just change
type: "POST"
instead of
type: "GET"
in my ajax code, and problem is solved, thanks for everyone, especially HMR
this is my php code:
<?php
ob_start();
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include '../ayar.php';
$tablo="kullaniciTB";
$durum='';
if(!isset($_SESSION["login"])){
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else{
if (empty($_SESSION['count'])) {
$_SESSION['count'] = 1;
$durum='count: ' . $_SESSION['count'];
} else {
$_SESSION['count']++;
}
}
$kadi = $_POST['kadi'];
$sifre = $_POST['sifre'];
if($kadi=='' or $sifre=='') {
$yazi="xbosx";
}
else if(strstr($kadi, '=') or strstr($kadi, '\'') or strstr($kadi, '--')){
$yazi="yhacky";
}
else{
$cptDurum="";
if($_SESSION['count']>4){
$kntrl = $_POST['cpthc'];
if($kntrl==''){
$cptDurum="bos";
}
else if($kntrl==$_SESSION['sifre']){
$cptDurum="dogru";
}
else if($kntrl!=$_SESSION['sifre']){
$cptDurum="yanlis";
}
}
if($cptBos=="dogru"){
$sorgu="SELECT * FROM `" . $tablo . "` WHERE kullaniciAdi='".$kadi."' AND sifre='".$sifre."' AND yetki=1";
if ($sonuc = mysqli_query($conn, $sorgu)) {
/* fetch associative array */
while ($deger = mysqli_fetch_assoc($sonuc)) {
$_SESSION["vaktiGeldi"] = time() + 5400;
$_SESSION["login"] = true;
$_SESSION["user"] = $kadi;
$_SESSION["userID"] = $deger['id'];
$durum="kdogruk";
}
/* free sonuc set */
mysqli_free_result($sonuc);
}
}
else if($cptDurum=="bos"){
$durum="cptBos";
}
else if($cptDurum=="yanlis"){
$durum="cptYanlis";
}
}
}
else{
$durum="mzatenm";
}
echo $durum;
?>

Redirect in Plupload

Wonder if someone can advise please - I am using Plupload and need to redirect to a different page to add information into a database.
I can upload the file perfectly, but I cannot seem to get it to redirect.
Ive tried putting in the code into "UploadComplete" and in a different test into "FileUploaded"
Using Firebug I put in breaks into the script and both sections are stopped at at the start, but when the file is finished it doesnt touch either of them.
Therefore I thought Id put it into the upload.php file in the Chunks section (as per a google result suggested).
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
$mypi = $projid;
header("Location: addimg.php?file=" . $fileName . "&blid=" . $mypi);
die();
}
In debugging it went through and hit the redirect and the die following, then then it went back to the start of the "if (!chunks etc)" and run through it again, but never redirected.
What am I missing please! Im pulling out my hair to make this work.
Thanks in advance
Javascript:
var uploader = new plupload.Uploader({
browse_button: 'browse', // this can be an id of a DOM element or the DOM element itself
container: document.getElementById('upcontainer'), // ... or DOM Element itself
//url: 'upload.php',
url: 'uploader_plup/upload.php?wts=<?php echo $projid;?>',
chunk_size: '2mb',
max_retries: '5',
// Sort files
sortable: true,
// Specify what files to browse for
filters : {
mime_types:[
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"},
{title : "Video files", extensions : "mov,mp4,mpeg,avi,mpg,wmv,w4v,flv,ogv,divx,asf,asx,ram,m2v"},
{title : "PDF files", extensions : "pdf"},
{title : "Text files", extensions : "htm,html,doc,txt,rtf,ppt"}
],},
}
);
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
var html = '';
plupload.each(files, function(file) {
html += '<li id="' + file.id + '">' + file.name + ' ('+plupload.formatSize(file.size) + ') <b></b></li>';
});
document.getElementById('filelist').innerHTML += html;
});
uploader.bind('FileUploaded', function(up, file, info) {
// Called when file has finished uploading
log('[FileUploaded] File:', file, "Info:", info);
});
uploader.bind('ChunkUploaded', function(up, file, info) {
// Called when file chunk has finished uploading
log('[ChunkUploaded] File:', file, "Info:", info);
});
uploader.bind('UploadProgress', function(up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
log('[UploadProgress] File:', file, "Info:", info);
});
uploader.bind('UploadComplete', function(up, files) {
// Called when file has finished uploading
// console.log("[UploadComplete]");
// backButtonState = true;
var totup = uploader.total.uploaded + 1;
var fillen = uploader.files.length;
if(totup == fillen)
{
var mypi = "<?php echo $projid; ?>";
window.location = "addimg.php?file="+files+"&blid="+mypi;
}
log('[UploadComplete]');
});
uploader.bind('Error', function(up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
log('[Error] File:', file, "Info:", err.message);
});
document.getElementById('start-upload').onclick = function() {
uploader.start();
};
function log() {
var str = "";
plupload.each(arguments, function(arg) {
var row = "";
if (typeof(arg) != "string") {
plupload.each(arg, function(value, key) {
// Convert items in File objects to human readable form
if (arg instanceof plupload.File) {
// Convert status to human readable
switch (value) {
case plupload.QUEUED:
value = 'QUEUED';
break;
case plupload.UPLOADING:
value = 'UPLOADING';
break;
case plupload.FAILED:
value = 'FAILED';
break;
case plupload.DONE:
value = 'DONE';
break;
}
}
if (typeof(value) != "function") {
row += (row ? ', ' : '') + key + '=' + value;
}
});
str += row + " ";
} else {
str += arg + " ";
}
});
var log = document.getElementById('console');
log.innerHTML += str + "\n";
}
</script>
Try this way:
uploader.bind('UploadComplete', function(up, files) {
// Called when all files are either uploaded or failed
var mypi = "<?php echo $projid; ?>";
window.location = "addimg.php?file="+files+"&blid="+mypi;
/* This is not necessary since UploadComplete means all is done!
var totup = uploader.total.uploaded + 1;
var fillen = uploader.files.length;
if(totup == fillen) {}
log('[UploadComplete]');*/
});
And remove this php line:
header("Location: addimg.php?file=" . $fileName . "&blid=" . $mypi);

How can I return the path of a screenshot capture to a function and return via JSON to javascript?

I have a PHP script that invokes a casperjs script via exec function and this is working fine.
Is it possible to return the path where I saved a screenshot via exec as JSON?
My scripts are below:
PHP code:
// Execute to CasperJS via asynchronous process
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$target = $_POST['target'];
$filename = $_POST['file'];
$retorno = array()
try {
exec("{$casperjs_run} {$script} {$username} {$password} {$filename} 2>&1", $output);
} catch (Exception $e) {
$retorno['error404'] = "Desculpe! Não foi possivel acessar a página solicitada.";
}
// Return Data if success
// Retorna para front-end
if (empty($output)){
$retorno['success'] = $output;
echo json_encode($retorno);
return false;
} else {
$retorno['error'] = $output;
echo json_encode($retorno);
return false;
}
?>
CasperJS code:
casper.thenOpen(minhaoi, function myaccount() {
this.capture('pic2.png');
this.log('Acessando informações da conta, aguarde...');
if (!this.exists(('div.panel-horizontal'))) {
this.log(JSON.stringify("Não foi encontrado um plano colaborador, aguarde..."));
noDetails = this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
} else {
casper.waitForResource("Análise de Conta", function orderDetails(details) {
return details;
}, function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
}
});
// Logout & Exit
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
return noDetails;
} else {
return myDetails;
}).run();
Here my JS code that receive the information from casperjs via JSON.
Javascript Code:
success: function(data) {
if (data.success) {
$('#retorno').html(data.success);
$('#imagem').attr('src', '/details/' + filename);
$('#resultado').show();
}
},
error: function(data) {
// check error
$('#retorno').attr("class='alert alert-danger' role='alert'");
$('#retorno').html(data.error);
}
In my mind filename should be the whole name of the screenshot like this, pi9rxw2fqlh.png plus the complete path too. And display the image in the browser.
What's wrong in my approach?
For this.log to actually print something, you need to set the logLevel to at least debug as it is the default log level. So either increase the log level casper.options.logLevel = 'debug'; or use this.echo instead of this.log.
It looks like you're using waitForResource wrong. Since there can't be resources with spaces in them, you might want to checkout waitForText under the assumption that the loaded resource adds that string to the DOM:
casper.waitForText("Análise de Conta", function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
capture as well as captureSelector return the casper instance and not the image details. So you need to pass the filename.
Since you use php's exec with the output array, you can casper.echo the filename in question with a unique beginning string (here #noDetails#):
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
this.echo("#noDetails#" + filename + ".png");
In the client javascript you can then iterate over the data.success or data.error arrays and extract the filename from the match line:
data.success.forEach(function(line){
if (line.indexOf("#noDetails#") === 0) {
var filename = line.split("#noDetails#")[1];
$('#imagem').attr('src', '/details/' + filename);
}
});
With this, you can completely remove the if block from the eachThen callback.
The other option is to set the specific screenshot variable and write the JSON object in the last line.
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
noDetails = filename + ".png";
and at the end:
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
this.echo(JSON.stringify({filename:noDetails}));
} else {
this.echo(JSON.stringify({filename:myDetails}));
}
});
On the client side, you would need to only look in the last line of the array:
var obj = JSON.parse(data.success[data.success.length-1]);
$('#imagem').attr('src', '/details/' + obj.filename);

php session_id change on header redirect

What I am trying to do is increment the value inside the COOKIE in every redirect... but every time I check if the cookie exists it doesn't.
I try to do it with a SESSION also, but the session_id changes in each redirect (I am guessing that the redirect create a new session for some reason )
This is my code
<script language="javascript">
var popexurl = "<?php echo $PopExitUrl ?>";
if(popexurl != ""){
(function() {
setTimeout(function() {
<?php
if (isset($_COOKIE["count"]))
{
//cheak user refreshes
$cookie = (int)++$_COOKIE['count'];
setcookie("count", $cookie, time()+3600);
}
else
{
setcookie("count", 1, time()+3600);
$cookie=0;
}
?>
var __redirect_to = '<?php echo $PopExitUrl; ?>';//
var _tags = ['button', 'input', 'a'], _els, _i, _i2;
for(_i in _tags) {
_els = document.getElementsByTagName(_tags[_i]);
for(_i2 in _els) {
if((_tags[_i] == 'input' && _els[_i2].type != 'button' && _els[_i2].type != 'submit' && _els[_i2].type != 'image') || _els[_i2].target == '_blank') continue;
_els[_i2].onclick = function() {window.onbeforeunload = function(){};}
}
}
window.onbeforeunload = function() {
window.scrollTo(0,0);
document.getElementById('ExitBackDiv').style.display = 'block';
document.getElementById('ExitDiv').style.display = 'block';
setTimeout(function() {
window.onbeforeunload = function() {};
setTimeout(function()
{
window.location = __redirect_to;
}, 500);
},5);
<?php
if ($PopupMessage == ""){
$PopupMessage= "\\n**********************\\nWAIT! WAIT! WAIT! WAIT!\\n\\n**********************\\n\\nDont Miss This LAST CHANCE to become Financially Secure and CHANGE YOUR Lifestyle!!!\\n\\n...Click STAY ON THIS PAGE to activate your LIMITED time offer!";}
?>
var popmsg = "<?php echo $PopupMessage ?>";
if (navigator.userAgent.indexOf("Firefox")!=-1)
{
//setTimeout('window.location="'+__redirect_to+'"', 10);
window.alert(popmsg);
return popmsg;
}
else
{
return popmsg;
}
}
}, 500);
})();
}
</script>
session_start(); creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
PHP: session_start()

Categories

Resources