PDA

View Full Version : js progress bar issue



ianhaney
01-24-2016, 09:11 PM
Hi

Sorry got a new issue on another project I am working on

it's a file upload project that has the multiple files upload feature stored on the server in a folder and a select and delete feature as well but the progress bar part is not working that shows the user the progress as a percentage for their uploaded files

I think the js is conflicting with the delete image part but not 100%, below is the scripts

memberpage.php



<div class="status"></div>

<form action="uploader.php" method="post" enctype="multipart/form-data">
<input type="file" id="files" name="files[]" multiple="multiple" required="required" />
<input type="submit" value="Upload!" />
</form>

<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>

<h1>Your Images</h1>

<form method="post" action="deletepho.php">
<center>
<input type="submit" value="Delete" name="Delete">
</center>
<?php
//lets assign the folder name in $title
//You can assign any name
$title= "user-images";
/*$directory corresponds to whole path. Edit to your preference. (i assume u store your
images in directory named "images")*/
$directory = "user-images";
//The array specifies the format of the files
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;

$dir_handle = @opendir($directory) or die("There is an error with your image directory!");

while ($file = readdir($dir_handle))
{
if($file=='.' || $file == '..') continue;

$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));

$title = implode('.',$file_parts);
$title = htmlspecialchars($title);

$nomargin='';

if(in_array($ext,$allowed_types))
{
if(($i+1)%4==0)
$nomargin='nomargin';
echo'
<div id="picture">
<img src="'.$directory.'/'.$file.'">
<br>
Select <input type="checkbox" value="'.$directory.'/'.$file.'" name="imgfile[]">
</div>';
}
$i++;
}

closedir($dir_handle);
//Now we have the list of images within form elements
?>
</form>


uploader.php script



<?php
//define page title
$title = 'Uploaded Successful';

//include header template
require('layout/header.php');

$max_size = 1024*200;
$extensions = array('jpeg', 'jpg', 'png', 'gif');
$dir = 'user-images/';
$count = 0;

if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files']))
{
// loop all files
foreach ( $_FILES['files']['name'] as $i => $name )
{
// if file not uploaded then skip it
if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
continue;

// skip large files
if ( $_FILES['files']['size'][$i] >= $max_size )
continue;

// skip unprotected files
if( !in_array(pathinfo($name, PATHINFO_EXTENSION), $extensions) )
continue;

// now we can move uploaded files
if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $dir . $name) )
$count++;
}

echo json_encode(array('count' => $count));

}

//include header template
require('layout/footer.php');
?>


script.js - FOR THE PROGRESS BAR PART



$ (function() {

/* variables */
var status = $('.status');
var percent = $('.percent');
var bar = $('.bar');

/* submit form with ajax request using jQuery.form plugin */
$('form').ajaxForm({

/* set data type json */
dataType:'json',

/* reset before submitting */
beforeSend: function() {
status.fadeOut();
bar.width('0%');
percent.html('0%');
},

/* progress bar call back*/
uploadProgress: function(event, position, total, percentComplete) {
var pVel = percentComplete + '%';
bar.width(pVel);
percent.html(pVel);
},

/* complete call back */
complete: function(data) {
status.html(data.responseJSON.count + ' Files uploaded!').fadeIn();
}

});
});


deletepho.php


<?php

//define page title
$title = 'Successfully Deleted Photo(s)';

//include header template
require('layout/header.php');

$file = $_REQUEST['imgfile'];
$num_files=count($file);
for($i=0;$i<$num_files;$i++)
{
unlink ("$file[$i]");
}
echo '<div class="container">';
echo '<div class="row">';
echo '<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">';
echo '<br><br>';
echo 'Image(s) successfully deleted.';
echo '<hr>';
echo '<a href="memberpage.php">back to profile page</a>';
echo '</div>';
echo '</div>';
echo '</div>';

//include header template
require('layout/footer.php');

?>

ianhaney
01-25-2016, 09:26 AM
I have been playing with the coding again and got the progress bar working now but the script is not uploading the images to the folder on the server

below is my new script on script.js



jQuery('document').ready(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
dataType: 'script',
url: "{{=URL('default', 'user_song_form')}}",
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
status.html('Thank You Upload Complete!');
}
});
});


below is my new script on memberpage.php



<?php require('includes/config.php');

$memberID = $_SESSION["memberID"]; // store the user id into session

//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }

//define page title
$title = 'Members Page';

//include header template
require('layout/header.php');
?>

<div class="container">

<div class="row">

<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">

<h2>Member only page - Welcome <?php echo $_SESSION['username']; ?></h2>
<hr />

<form action="uploader.php" method="post" enctype="multipart/form-data">
<input type="file" id="files" name="files[]" multiple="multiple" required="required" />
<input type="submit" value="Upload!" />
</form>

<div class="progress">
<div class="bar"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>

<hr>

</div>
</div>
</div>

<div class="container">

<div class="row">

<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">

<h1>Your Images</h1>

<form method="post" action="deletepho.php">
<center>
<input type="submit" value="Delete" name="Delete">
</center>
<?php
//lets assign the folder name in $title
//You can assign any name
$title= "user-images";
/*$directory corresponds to whole path. Edit to your preference. (i assume u store your
images in directory named "images")*/
$directory = "user-images";
//The array specifies the format of the files
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;

$dir_handle = @opendir($directory) or die("There is an error with your image directory!");

while ($file = readdir($dir_handle))
{
if($file=='.' || $file == '..') continue;

$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));

$title = implode('.',$file_parts);
$title = htmlspecialchars($title);

$nomargin='';

if(in_array($ext,$allowed_types))
{
if(($i+1)%4==0)
$nomargin='nomargin';
echo'
<div id="picture">
<img src="'.$directory.'/'.$file.'">
<br>
Select <input type="checkbox" value="'.$directory.'/'.$file.'" name="imgfile[]">
</div>';
}
$i++;
}

closedir($dir_handle);
//Now we have the list of images within form elements
?>
</form>

<hr />

<p><a href='logout.php'>Logout</a></p>

</div>
</div>
</div>

<?php
//include header template
require('layout/footer.php');
?>


below is the code from my layout/header.php file



<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.form.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>

ianhaney
01-25-2016, 09:28 AM
I think it is a issue with the following line



<script type="text/javascript" src="js/jquery.min.js"></script>


because when I hide that line, the uploader works and uploads the images but the progress bar does not work?

Any ideas please

Thank you in advance

Ian

styxlawyer
01-25-2016, 01:20 PM
I think it is a issue with the following line



<script type="text/javascript" src="js/jquery.min.js"></script>


because when I hide that line, the uploader works and uploads the images but the progress bar does not work?

Any ideas please

Thank you in advance

Ian

The progress bar requires the jQuery library to be loaded so if you don't load it the bar won't work. I've had a look at your code but there's too much "noise" to see what's happening. Try putting a simplified set of pages on a server somewhere.

You might also want to look at this page (http://www.sanwebe.com/2012/05/ajax-image-upload-with-progressbar-with-jquery-and-php).

ianhaney
01-25-2016, 02:36 PM
You might also want to look at this page (http://www.sanwebe.com/2012/05/ajax-image-upload-with-progressbar-with-jquery-and-php).

Thank you so much for the link, I have put that in and it works but just a couple of issues if you can help please

Is there a way so that it does not upload a large version as well as and a thumbnail version of the image, I only want the thumbnail version to show if possible and also after upload, is there a way the page can refresh itself to show the images uploaded please?

Hope that makes sense

ianhaney
01-25-2016, 03:07 PM
Sorry its actually loading the original images all ok but is resizing the images and creating thumbnail images so end up with the original images and then the resized thumbnail images where as I want just want the original images uploaded and not have it resize and upload the resized images as well

styxlawyer
01-25-2016, 05:26 PM
I haven't looked at that code but I would guess that the thumbnail is actually created on the server after upload (see here (http://www.imagemagick.org/script/index.php)). Thumbnails are often quite useful so could be left or if you really don't want it you could just delete it after the upload has finished.

The quickest way to get a PHP page to refresh itself is to include this code as the very last line after the upload has finished:



header("Location: http://your.page.address.here");


Use this with great caution as you can easily get into an endless loop where the page continuously refreshes.

ianhaney
01-25-2016, 10:10 PM
do you know of any other scripts that don't create a thumbnail, but needs to have a progress bar ideally along with multiple file uploads and the page refresh

I looked on Google but have looked at most of them and don't do everything needed or don't work

ianhaney
01-26-2016, 10:26 AM
I am now using this script and works perfect apart from one little issue

http://www.phpgang.com/how-to-upload-multiple-images-jquery-ajax-using-php_453.html

I can't work out where to put the code to make the page refresh automatically after upload so I can see the uploaded images

the code with the upload form is below



<?php
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
?>

<?php require('includes/config.php');

$memberID = $_SESSION["memberID"]; // store the user id into session

//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }

//define page title
$title = 'Members Page';

//include header template
require('layout/header.php');
?>

<div class="container">

<div class="row">

<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">

<h2>Member only page - Welcome <?php echo $_SESSION['username']; ?></h2>
<hr />

<div id="mulitplefileuploader">Upload</div>

<div id="status"></div>
<script>

$(document).ready(function()
{

var settings = {
url: "upload.php",
method: "POST",
allowedTypes:"jpg,png,gif,jpeg",
fileName: "myfile",
multiple: true,
onSuccess:function(files,data,xhr)
{
$("#status").html("<font color='green'>Upload is success</font>");
},
afterUploadAll:function()
{
alert("all images uploaded!!");

},

onError: function(files,status,errMsg)
{
$("#status").html("<font color='red'>Upload is Failed</font>");
}
}
$("#mulitplefileuploader").uploadFile(settings);

});

</script>

<hr>

</div>
</div>
</div>

<div class="container">

<div class="row">

<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">

<h1>Your Images</h1>

<form method="post" action="deletepho.php">
<center>
<input type="submit" value="Delete" name="Delete">
</center>
<?php
//lets assign the folder name in $title
//You can assign any name
$title= "user-images";
/*$directory corresponds to whole path. Edit to your preference. (i assume u store your
images in directory named "images")*/
$directory = "user-images";
//The array specifies the format of the files
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;

$dir_handle = @opendir($directory) or die("There is an error with your image directory!");

while ($file = readdir($dir_handle))
{
if($file=='.' || $file == '..') continue;

$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));

$title = implode('.',$file_parts);
$title = htmlspecialchars($title);

$nomargin='';

if(in_array($ext,$allowed_types))
{
if(($i+1)%4==0)
$nomargin='nomargin';
echo'
<div id="picture">
<img src="'.$directory.'/'.$file.'">
<br>
Select <input type="checkbox" value="'.$directory.'/'.$file.'" name="imgfile[]">
</div>';
}
$i++;
}

closedir($dir_handle);
//Now we have the list of images within form elements

?>
</form>

<br />

<a href="memberpage.php">Refresh</a>

<hr />

<p><a href='logout.php'>Logout</a></p>

</div>
</div>
</div>

<?php
//include header template
require('layout/footer.php');
?>


below is the upload.php script



<?php
$output_dir = "user-images/";

if(isset($_FILES["myfile"]))
{
$ret = array();

$error =$_FILES["myfile"]["error"];
{

if(!is_array($_FILES["myfile"]['name'])) //single file
{
$RandomNum = time();

$ImageName = str_replace(' ','-',strtolower($_FILES['myfile']['name']));
$ImageType = $_FILES['myfile']['type']; //"image/png", image/jpeg etc.

$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
$ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
$NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $NewImageName);
//echo "<br> Error: ".$_FILES["myfile"]["error"];

$ret[$fileName]= $output_dir.$NewImageName;

}
else
{
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++)
{
$RandomNum = time();

$ImageName = str_replace(' ','-',strtolower($_FILES['myfile']['name'][$i]));
$ImageType = $_FILES['myfile']['type'][$i]; //"image/png", image/jpeg etc.

$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
$ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
$NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

$ret[$NewImageName]= $output_dir.$NewImageName;
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$NewImageName );

}

}

}

echo json_encode($ret);

}

?>

styxlawyer
01-26-2016, 11:22 AM
You will probably have to use a JavaScript redirect rather than PHP. Put this in your first file and it should automatically reload after the alert is dismissed:



afterUploadAll:function()
{
alert("all images uploaded!!");
window.location.href = "your.upload.filename.php";
},

ianhaney
01-26-2016, 11:48 AM
You will probably have to use a JavaScript redirect rather than PHP. Put this in your first file and it should automatically reload after the alert is dismissed:



afterUploadAll:function()
{
alert("all images uploaded!!");
window.location.href = "your.upload.filename.php";
},


Thank you so much, it works perfect

styxlawyer
01-26-2016, 12:08 PM
You're welcome.