I edit multiple image upload scripts.
I added the features of uploading up to 3 photos and not uploading files larger than 5mb. It works successfully.
-- But I couldn't figure out how to define the text fields I added on js and how to send it to php document with post action.
Could you help?
I am posting the codes below.
php code:
<?php
$dts = $_POST['dts'];
$ttt = explode(',',$dts);
$others_image_last='';
$image_link="/upload_img/"; //folder name
for($i=0; $i<sizeof($_FILES['upload_files']['name']); $i++) {
if (in_array($i+1, $ttt)){}else{
$new_file = md5(microtime());
$image_type = $_FILES["upload_files"]["type"][$i];
$image_name = $_FILES["upload_files"]["name"][$i];
$image_error = $_FILES["upload_files"]["error"][$i];
$image_temp_name = $_FILES["upload_files"]["tmp_name"][$i];
print_r($image_temp_name);
if (($image_type == "image/jpeg") || ($image_type == "image/png") || ($image_type == "image/pjpeg") || ($image_type == "image/jpg")) {
$test = explode('.', $image_name);
$name = $new_file.'.'.end($test);
$url = '.'.$image_link. $name;
$info = getimagesize($image_temp_name);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($image_temp_name);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($image_temp_name);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($image_temp_name);
imagejpeg($image,$url,80);
}
echo $name;
/****** insert query here ******/
}
}?>
Html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Multiple Photo Upload</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<style>
.suggested-posts-article{
background: white;
-moz-box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
-webkit-box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
display: inline-block;
margin: 5px;
width: 23%;
}
article, aside, details, figcaption, figure, footer, header, main, nav, section {
display: block;
}
article, aside, footer, header, hgroup, main, nav, section {
display: block;
}
.suggested-posts-articlees {
display: inline-block;
width: 49.5%;
}
#media screen and (max-width:450px) {
.suggested-posts-article {
width:40% !important;
}
}
.more-photos:after{ right: 3px !important;
bottom: 0px !important;}
article, aside, details, figcaption, figure, footer, header, main, nav, section {
display: block;
}
.posts_article {
background-color: #333;
background-position: 50%;
background-size: cover;
margin-bottom: 2px;
padding-bottom: 63.5%;
}
#media screen and (max-width:450px) {
.suggested-posts-article {
width:40% !important;
}
}
.more-photos:after{ right: 3px !important;
bottom: 0px !important;}
.more-photos{
cursor:pointer !important;
}
.bluess {
width:100%;
margin:10px;
}
.btn-group-sm>.btn, .btn-sm {
padding: .25rem .5rem;
font-size: .875rem;
line-height: 1.5;
border-radius: .2rem;
}
.btn-outline-secondary {
color: #868e96;
background-color: transparent;
background-image: none;
border-color: #868e96;
}
.btnxc {
display: inline-block;
padding: .5rem .75rem;
border:1px solid #868e96;
margin:3px;
padding: .25rem .5rem;
font-size: .875rem;
line-height: 1.5;
border-radius: .2rem;
color:#868e96;
}
.rrrr{
color:red;
fill:red;
}
.rrrr2{
background-color: red;
}
.datepost{
margin-top:-15px;
}
.anther_ma
{
margin:1px;
}
.set_process
{
margin: 0px 7px 0px 0px;
}
.messaf{display:none;}
.progress{
width:80%;
}
.success_msg{
color:green;
display:none;
}
#post_send{
margin:8px 0 8px 0;
}
.fa_p{
margin-right:20px;
margin-top:10px;
border:0px;
z-index:9999
}
.p_run_div{
margin-top:-7px;
border-radius:0px;
padding:0px;
margin-bottom:8px;
display:none;
}
.btnxc{
margin-left:15px;
cursor:pointer;
}
.btnxc_r{
margin-left:15px;
display:none;
}
</style>
<div class="container">
<div class="row">
<div class="col-md-8">
<h2>Multiple Photo Upload</h2>
<div class="form-group">
<label for="examplename">Name</label>
<input type="text" class="form-control" id="examplename" placeholder="First Name">
</div>
<div class="form-group">
<label for="examplesurname">First Name</label>
<input type="text" class="form-control" id="examplesurname" placeholder="Last Name">
</div>
<div><button class="imgbuts btn btn-success" style='float:left'>Choose Photo...</button> <div id="uyari" style='float:left'>You can upload 3 photos.<br>
Each photo should not be larger than 5 mb.</b></div></div>
<div style="clear:both"></div>
<form action="method" name="upload-file" class="main_form" id="form-upload-file" enctype="multipart/form-data">
<div class="ui-block">
<aside class="suggested-posts">
<div class="suggested-posts-container">
<div class="row" id="message_box"></div>
</div>
</aside>
</div>
</form>
<button class="btn btn-primary btn-md-2 " id='post_send' onclick="save_muliple_image()">Upload</button>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width:0%">
<span class="sr-only">0</span>
</div>
</div>
<h2 class="success_msg">Photo upload completed.</h2>
</div>
</div>
</div>
<script>
var xp = 0;
var input_btn = 0;
var dts = [];
$(document).on("click", ".imgbuts", function (e) {
if(xp < 3){
input_btn++;
$("#form-upload-file").append(
"<input type='file' style='display:none;' name='upload_files[]' id='filenumber" +
input_btn +
"' class='img_file upload_files' accept='.gif,.jpg,.jpeg,.png,' multiple/>"
);
$("#filenumber" + input_btn).click();
} else {
uyari.innerHTML = ' You can upload up to 3 photos.';
}
});
$(document).on("change", ".upload_files", function (e){
files = e.target.files;
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
xp++;
var f = files[i];
var boyut = f.size;
var res_ext = files[i].name.split(".");
var img_or_video = res_ext[res_ext.length - 1];
var fileReader = new FileReader();
var yuvarlama = (boyut / (1024*1024)).toFixed(2) + ' mb';
uyari.innerHTML = '';
if (boyut > 5000000) {uyari.innerHTML = ' File size larger than 5mb'; xp--; return;}
fileReader.name = f.name;
fileReader.onload = function (e) {
var file = e.target;
$("#message_box").append(
"<article class='suggested-posts-article remove_artical" +
xp +
"' data-file='" +
file.name +
"'><div class='posts_article background_v" +
xp +
"' style='background-image: url(" +
e.target.result +
")'></div><div class='p_run_div'><span class='pp_run progress_run" +
xp +
"' style='opacity: 1;'></span></div><p class='fa_p p_for_fa" +
xp +
"'><span class='cancel_mutile_image btnxc cancel_fa" +
xp +
"' deltsid='"+0+"'><b>✖ SİL</b></span><span class='btnxc btnxc_r' >✔</span><span style='float:right'>"+ yuvarlama +"</span></p></article>"
);
};
fileReader.readAsDataURL(f);
}
});
function save_muliple_image() {
suggested = $(".suggested-posts-article").length;
if (suggested > 0) {
$(".cancel_mutile_image").prop("disabled", true);
$("#post_send").prop("disabled", true);
var formData = new FormData(document.getElementById("form-upload-file"));
formData.append("dts", dts);
var xhr = new window.XMLHttpRequest();
$.ajax({
url: 'upload_ajax.php',
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function (data) {
$(".main-content").find(".message-loading-overlay2").remove();
},
error: function (e) {
$("#preview_file_div ul").html(
"<li class='text-danger'>Something wrong! Please try again.</li>"
);
},
xhr: function (e) {
xhr.upload.addEventListener(
"progress",
function (e) {
console.log(e);
if (e.lengthComputable) {
var percentComplete = ((e.loaded || e.position) * 100) / e.total;
if(percentComplete==100){
$(".progress-bar").width(percentComplete + "%").html('99' + "%");
}else{
var yuzde = Math.floor(percentComplete);
$(".progress-bar").width(percentComplete + "%").html(yuzde + "%"); }
}
},
false
);
xhr.addEventListener("load", function (e) {
$('.progress-bar').css("background","#5cb85c").html('100' + "%");
$(".btnxc_r").show();
$(".success_msg").show();
$(".cancel_mutile_image").remove();
});
return xhr;
},
});
} else {
$(".messaf").show();
}
}
var rty=0;
$(document).on("click", ".cancel_mutile_image", function (e) {
$('.cancel_mutile_image').each(function(){
chk_id = $(this).attr('deltsid');
if(chk_id==0){ rty++; $(this).attr('deltsid',rty); }
});
deltsid = $(this).attr('deltsid');
dts.push(deltsid);
$(this).parents(".suggested-posts-article").remove();
xp--;
});
</script>
</body>
</html>
Uploading multiple files in php can be tricky but the trick you need to use here is that instead of using name="upload" in input filed use name="upload[]" it returns an array so it makes the code much cleaner ... And to upload files use loops ( I used for loop in to see demonstrate how to upload different files here ) you can write some js and before uploading add some validations as per your needs !
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$path = "./"; // Specifiy the path where uploaded files goes
// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);
// Loop through each file
for ($i = 0; $i < $total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a file path
if ($tmpFilePath != "") {
$target_path = $path;
$target_path = $target_path.basename($_FILES['upload']['name'][$i]);
// Upload files (YOUR IMAGES) into desired directory !
if (move_uploaded_file($tmpFilePath, $target_path)) {
$success = "success";
}
}
}
}
?>
<form action="index.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="upload[]" multiple />
<button type="submit">Submit</button>
</form>
Related
I can upload the image to a new folder, but the main things is need to display it out from that folder to PDF. Then I am using FDPF, but then I get an error message when displaying:
"Uncaught Exception: FPDF error: Can't open image file: Tulips.jpg "
But when i echo the $img it display. Then i add on $img in pdf->Image($img) it wont work it appear above message error.
Here is what I have try to code htmltopdf.html
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function ValidateSingleInput(oInput) {
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
oInput.value = "";
return false;
}
}
}
return true;
}
function handleFileSelect(event)
{
console.log(event)
var input = this;
if (input.files)
{
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++)
{
var reader = new FileReader();
console.log(reader)
reader.onload = (function (e)
{
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="',e.target.result, '" title="', escape(e.name), '"/><span class="remove_img_preview"></span>'].join('');
document.getElementById('preview').insertBefore(span, null);
});
reader.readAsDataURL(input.files[i]);
}
}
}
$(document).ready(function(){
// Listen to click event on the submit button
$('#submit').click(function (e) {
e.preventDefault();
var myform = document.getElementById("form");
var fd = new FormData(myform);
$.ajax({
url:"upload1.php",
type:"POST",
data:fd,
//dataType: 'json',
processData: false,
contentType: false,
cache: false,
success:function(data){
alert("Success Insert!");
},
});
});
$('#fileToUpload').change(handleFileSelect);
//preview image and remove
$('#preview').on('click', '.remove_img_preview',function ()
{
$(this).parent('span').remove();
$("#fileToUpload").val("");
});
});
</script>
<style>
div.relative {
position: relative;
top: -300px;
}
#bottom{
position: relative;
right: 0;
bottom: 0;
}
.thumb
{
width: 100px;
height: 100px;
margin: 0.2em -0.7em 0 0;
}
.remove_img_preview
{
position:relative;
top:-25px;
right:5px;
background:black;
color:white;
border-radius:50px;
font-size:0.9em;
padding: 0 0.3em 0;
text-align:center;
cursor:pointer;
}
.remove_img_preview:before
{
content: "×";
}
table,th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
textarea {
width: 100%;
height: 300px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
font-size: 16px;
resize:none;
}
table.menu {
border: 1px solid black;
border-collapse: collapse;
width: 10%;
float:right;
}
</style>
<body>
<form action="generate_pdf.php" method="POST" id="form">
<input type="submit" value="Send" id="submit" name="submit"><input type="reset" value="Clear">
<input type="file" name="fileToUpload[]" id="fileToUpload" onchange="ValidateSingleInput(this);" multiple = "multiple" style="display: none;">
<input type="button" value="Browse..." onclick="document.getElementById('fileToUpload').click();" />
<input type="submit" value="PDF">
<div id="preview"></div>
</form>
</body>
</html>
Here is the upload1.php
<?php
require 'config.php';
$year = date("yy");
$year = substr($year, -2);
$month = date("m");
$key = "KM".$year.$month;
$total = count($_FILES['fileToUpload']['name']);
$sql = "SELECT * FROM images WHERE id LIKE '$key%' ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
//GET NEW RUNNING NUMBER BY CHECKING DATABASE
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$number = sprintf('%03d',substr($row['id'], -3)+ 1) ;
$ans = $key.$number;
}
}
else
{
$ans = $key."001";
}
$target_dir = "D:/XAMPP/htdocs/new3/new3/uploads/" . $ans;
if(!file_exists($target_dir))
{
mkdir($target_dir,0777,true);
}
$sql = $conn->query ("INSERT INTO images (id) VALUES ('$ans')");
$allowed = array('gif', 'png', 'jpg','xlsx','pdf','doc');
$ext = pathinfo($total, PATHINFO_EXTENSION);
if (!in_array($ext, $allowed)) {
echo 'error';
}
for( $i=0 ; $i < $total ; $i++ )
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$i], $target_dir."/".$ans."-".$_FILES["fileToUpload"]["name"][$i]))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"][$i]). " has been uploaded."."<br>";
}
else
{
echo "Sorry, there was an error uploading your file.";
}
}
?>
Here is the generate_pdf.php that i have try:
<?php
$img=$_FILES["fileToUpload"]["name"][0];
echo $img;
require 'fpdf181/fpdf.php';
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',10);
$pdf->Image($img,NULL,NULL,0,0,'PNG');
$pdf->Output();
?>
I don't know whether I wrote it correctly or not? Or just need to call back the path where image is stored and display it out? Myself already brainstorming, don't know how it works. Can anyone help? Maybe this is a duplicate questions but I can't even find any related things, just can found how to retrieve from database.
First problem is that your <form> tag is missing the enctype="multipart/form-data" attribute.
As for the PHP error, $_FILES["fileToUpload"] is an array, so $image=$_FILES["fileToUpload"]["name"] should change to $_FILES["fileToUpload"]["name"][0] (assuming you want the first file). So generate_pdf.php should start with:
$image=$_FILES["fileToUpload"]["name"][0];
After i have amend some of it the error come out is "Fatal error: Uncaught Exception: FPDF error: Can't open image file"
This is the code file i have amend call generate_pdf.php
$image=$_FILES["fileToUpload"]["name"][0];
$img="C:/xampp/htdocs/test/uploads/".$image;
require 'fpdf181/fpdf.php';
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',10);
$pdf->Image($img, NULL, NULL, 0, 0, 'png');
$pdf->Output();
The percentage of progress bar does not work correctly
The correct progress bar does not work and it's 100% fast
But the file has not uploaded yet
Click the submit button
The progress bar is completed quickly
But still the file is being uploaded
I'm interested in understanding the code forms
<?php
$msg = [
"title file"
,"url file"
,"send file"
];
?>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-rtl.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<script src="jquery.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js"></script>
<style>
.del {
border-radius: 100%;
display: inline-block;
font-size: 13px;
height: auto;
margin-right: 4px;
padding: 5px;
}
.box {
height: 41px;
padding-top: 2px;
vertical-align: middle;
}
#uploadurl {
border: 1px solid #ccc;
margin-bottom: 7px;
margin-top: 14px;
padding-top: 11px;
}
</style>
<script>
var template = '<div class="form-group box">' +
'<input type="text" class="col-sm-5 form-control" name="title[]" placeholder="<?=$msg[0]?>">' +
'<input type="text" class="col-sm-6 form-control" name="url[]" placeholder="<?=$msg[1]?>">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'<div class="progress-bar progress progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div></div>';
$(document).ready(function(){
$('.add').on('click',function (e) {
$("#uploadurl").append(template);
});
$(document).on('click','.del',function (e) {
var del = $(this).closest('.box').index();
$('.box').eq(del).remove();
});
$('#submit').click(function (e) {
e.preventDefault();
$("input[name='url[]']").each(function (index, value){
$('.myprogress').eq(index).css('width', '0');
var url = $(this).val();
var title = $("input[name='title[]']").eq(index).val();
if(title == ""){
title = <?=strtotime(date('Y-m-d h:s:i'))?>;
}else{
title =<?=strtotime(date('Y-m-d h:s:i'))?>+"_"+title;
}
var data = "url="+url+"&title="+title;
$.ajax({
type: 'POST',
url: "upload.php",
data: data,
datatype:"json",
// contentType: "application/x-www-form-urlencoded",
processData: false,
// this part is progress bar
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function (data) {
$('#fileupload').append("<a style='display: block' href='"+data+"'>"+data+"</a>");
}
});
});
});
});
</script>
<div class="container">
<form id="upload-form" method="post">
<div id="uploadurl" class="col-md-12">
<div class="form-group box">
<input type="text" class="col-sm-5 form-control" name="title[]" placeholder="<?=$msg[0]?>">
<input type="text" class="col-sm-6 form-control" name="url[]" placeholder="<?=$msg[1]?>">
<div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
</div>
</div>
<div style="display: block">
+
<input type="submit" class="btn btn-primary" id="submit" value="<?=$msg[2]?>" name="submit">
</div>
</form>
<div id="fileupload">
</div>
</div>
upload.php
$title = $_POST['title'];
$url = $_POST['url'];
$now = date('Y-m-d h:s:i');
$partition = date('Ym', strtotime($now));
$folder = "file/attach/".$partition."/";
if (!file_exists($folder)) {
$old = umask(0);
mkdir($folder, 0777);
umask($old);
}
$p = pathinfo($url);
$newfile = $folder.$title.".".$p['extension'];
if ( copy($url, $newfile) ) {
echo $newfile;
}else{
echo "false";
}
Click on the link below to view the demo
In the firebug you see, the file is still being uploaded
But the percentage of progress has been 100%.
demo
When I needed a progress bar to add to my file downloads(in my project); I used this code. I have tested this code also. Try the code below; I am quite sure it will serve your purpose:
<!doctype html>
<head>
<title>File Upload Progress Demo</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius:
10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding:
1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px;
}
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code><input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js">
</script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
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) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});
})();
</script>
</body>
</html>
My php upload file:
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error in the upload, please try again!";
}
?>
Hope it helps you and serve as a documentation for you...Happy coding
hello am building a form that uploads images, it works correctly, but i want to add something extra, to be able to specify what the image would saved as. this is what i have, code snippet
<?php
//upload.php
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
echo "Uploaded File :".$_FILES["myfile"]["name"];
}
}
?>
HTML:
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>Ajax File Upload Demo</h1>
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
</body>
</html>
Give this a try, however you'll need to do some work on certain validation.
It uses a form input <input type="text" name="upload_name"> to give it a custom name.
Tested
HTML form
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>Ajax File Upload Demo</h1>
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
Name it:
<input type="text" name="upload_name">
<br>
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
</body>
</html>
PHP
<?php
$upload_name = $_POST['upload_name'];
$idx = strpos($_FILES['myfile']['name'],'.');
$ext = substr($_FILES['myfile']['name'],$idx);
$file_name = $upload_name . $ext;
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
// move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
// echo "Uploaded File :".$_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$file_name);
echo "Uploaded File :" . $file_name;
}
}
?>
Footnotes:
Link to their project page http://malsup.com/jquery/form/ where you can download all the files, rather than fetching the JS from their website.
So im trying to have an upload with a progress bar, i installed uploadprogress pecl, and the upload worked perfectly if the action in the form leads to upload.php, any other name, and it stops working.
If the name is not upload.php the output is simply "100" (which can be seen why below with the getprogress.php file)
this is the form: (this versions works, as the file is upload.php)
<form method="post" action="/test/upload.php" enctype="multipart/form-data" id="upload-form" target="upload-frame">
<input type="hidden" id="uid" name="UPLOAD_IDENTIFIER" value="<?php echo $uid; ?>">
<input type="file" name="file">
<input type="submit" name="submit" value="Upload!">
</form>
</div>
<div style="float:left;width:100%;">
<div id="progress-bar"></div>
</div>
<iframe id="upload-frame" name="upload-frame"></iframe>
this is the jquery:
<script>
(function ($) {
var pbar;
var started = false;
$(function () {
$('#upload-form').submit(function() {
pbar = $('#progress-bar');
pbar.show().progressbar();
$('#upload-frame').load(function () {
started = true;
});
setTimeout(function () {
updateProgress($('#uid').val());
}, 1000);
});
});
function updateProgress(id) {
var time = new Date().getTime();
$.get('../uploadprogress/getprogress.php', { uid: id, t: time }, function (data) {
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
started = progress < 100;
updateProgress(id);
}
started && pbar.progressbar('value', progress);
});
}
}(jQuery));
</script>
this is the file getprogress.php
<?php
if (isset($_GET['uid'])) {
// Fetch the upload progress data
$status = uploadprogress_get_info($_GET['uid']);
if ($status) {
// Calculate the current percentage
echo round($status['bytes_uploaded']/$status['bytes_total']*100, 1);
}
else {
// If there is no data, assume it's done
echo 100;
}
}
?>
ive spent about 5 hours on this trying to figure out why, and i cant. help would be greatly appreciated.
You can use this class, without using jquery:
<?php
/**
* Progress bar for a lengthy PHP process
* http://spidgorny.blogspot.com/2012/02/progress-bar-for-lengthy-php-process.html
*/
class ProgressBar {
var $percentDone = 0;
var $pbid;
var $pbarid;
var $tbarid;
var $textid;
var $decimals = 1;
function __construct($percentDone = 0) {
$this->pbid = 'pb';
$this->pbarid = 'progress-bar';
$this->tbarid = 'transparent-bar';
$this->textid = 'pb_text';
$this->percentDone = $percentDone;
}
function render() {
//print ($GLOBALS['CONTENT']);
//$GLOBALS['CONTENT'] = '';
print($this->getContent());
$this->flush();
//$this->setProgressBarProgress(0);
}
function getContent() {
$this->percentDone = floatval($this->percentDone);
$percentDone = number_format($this->percentDone, $this->decimals, '.', '') .'%';
$content .= '<div id="'.$this->pbid.'" class="pb_container">
<div id="'.$this->textid.'" class="'.$this->textid.'">'.$percentDone.'</div>
<div class="pb_bar">
<div id="'.$this->pbarid.'" class="pb_before"
style="width: '.$percentDone.';"></div>
<div id="'.$this->tbarid.'" class="pb_after"></div>
</div>
<br style="height: 1px; font-size: 1px;"/>
</div>
<style>
.pb_container {
position: relative;
}
.pb_bar {
width: 100%;
height: 1.3em;
border: 1px solid silver;
-moz-border-radius-topleft: 5px;
-moz-border-radius-topright: 5px;
-moz-border-radius-bottomleft: 5px;
-moz-border-radius-bottomright: 5px;
-webkit-border-top-left-radius: 5px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
-webkit-border-bottom-right-radius: 5px;
}
.pb_before {
float: left;
height: 1.3em;
background-color: #43b6df;
-moz-border-radius-topleft: 5px;
-moz-border-radius-bottomleft: 5px;
-webkit-border-top-left-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
}
.pb_after {
float: left;
background-color: #FEFEFE;
-moz-border-radius-topright: 5px;
-moz-border-radius-bottomright: 5px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 5px;
}
.pb_text {
padding-top: 0.1em;
position: absolute;
left: 48%;
}
</style>'."\r\n";
return $content;
}
function setProgressBarProgress($percentDone, $text = '') {
$this->percentDone = $percentDone;
$text = $text ? $text : number_format($this->percentDone, $this->decimals, '.', '').'%';
print('
<script type="text/javascript">
if (document.getElementById("'.$this->pbarid.'")) {
document.getElementById("'.$this->pbarid.'").style.width = "'.$percentDone.'%";');
if ($percentDone == 100) {
print('document.getElementById("'.$this->pbid.'").style.display = "none";');
} else {
print('document.getElementById("'.$this->tbarid.'").style.width = "'.(100-$percentDone).'%";');
}
if ($text) {
print('document.getElementById("'.$this->textid.'").innerHTML = "'.htmlspecialchars($text).'";');
}
print('}</script>'."\n");
$this->flush();
}
function flush() {
print str_pad('', intval(ini_get('output_buffering')))."\n";
//ob_end_flush();
flush();
}
}
echo 'Starting…<br />';
$p = new ProgressBar();
echo '<div style="width: 300px;">';
$p->render();
echo '</div>';
for ($i = 0; $i < ($size = 100); $i++) {
$p->setProgressBarProgress($i*100/$size);
usleep(1000000*0.1);
}
$p->setProgressBarProgress(100);
echo 'Done.<br />';
?>
You can call the setProgressBarProgress function inside a while process, depending on your needs!!! It's great!.
I created a custom gallery and it works perfectly in internet explorer however in firefox and chrome it doesn't work like it should. The lightbox doesn't pop up on the clicking the thumbnail link, you have to click it twice, when clicked once the backdrop comes up but not the lightbox, but then on clicking the thumbnail twice it centers and pops up. And I have no clue why, please help.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Album</title>
<script type="text/javascript" src="hftpnyc/js/jquery-1.7.1.min.js"></script>
<link href="albums.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="Website/print.css" rel="stylesheet" type="text/css" media="print"/>
<style type="text/css">
body {
}
.backdrop
{ position:fixed;
top:0px;
left:0px;
width:100%;
height:100%;
background:black;
z-index:50;
display:none;
}
.smllpic a {text-decoration:none;}
.box
{margin:auto;
clear:both;
position:fixed;
max-height:705px;
max-width:905px;
background:black;
z-index:52;
padding:0px;
border:black 1.2px solid;
overflow:hidden;
}
.close
{
position:absolute;
right:6px;
margin-top:3px;
cursor:pointer;
font-size:20px;
font-family:acens;
font-weight:700px;
font-stretch:narrower;
opacity: .3;
}
.smllpic img{cursor:pointer; opacity:0.7; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70); };
}
</style>
</head>
<body>
<div id="contentcontainer" style="width:100%;clear:both;">
<div id="wrapper" style="width:981px; height:100%; margin:0px auto;">
<div style="margin:0px auto;width:979px;">
<h2 style="font-family:Tahoma, Geneva, sans-serif; color:#333;border-bottom:#A3308E solid 1px; background-color: #E6E6E6;"> Album </h2> </div>
<div style="float:right; margin-right:3px;">
<form action="" method="post">
<a href="Albums.php">
<input type="button" name="Uploadmre" value="Upload more" style="border: 1px solid #d0ccc9;right:0px;background: #fff;color: #5f95ef;font-size: 11px;font-weight: 700;height:22px; margin-right:7px;">
</a>
</form>
</div>
<div id="page-wrap" style=" width:918px; margin: 0px auto;clear:both;">
<?php
error_reporting(0);
/* function: returns files from dir */
function get_files($images_dir,$exts = array('jpeg','gif','png','jpg')) {
$files = array();
if($handle = opendir($images_dir)) {
while(false !== ($file = readdir($handle))) {
$extension = strtolower(get_file_extension($file));
if($extension && in_array($extension,$exts)) {
$files[] = $file;
}
}
closedir($handle);
}
return $files;
}
/* function: returns a file's extension */
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
$images_dir = 'hftpnyc/thumbs/';
$thumbs_dir = 'hftpnyc/thumbs/thumbnails/';
$thumbs_width = 100;
$images_per_row = 11;
$string = "";
/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file) {
$index++;
$thumbnail_image = $thumbs_dir.$file;
//if(!file_exists($thumbnail_image)) {
//$extension = get_file_extension($thumbnail_image);
//if($extension) {
//make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
//}
//}
error_reporting(0);
echo '<div class="smllpic" style=" padding: 0px; margin: 0px; border: 1px solid black; display: block; width: 100px; height:100px; float: left; "> <img id="thumbs" src="',$thumbnail_image,'" width="100px"/></div>';
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
}
}
else {
echo '<p>There are no images in this gallery.</p>';
}
?>
</div>
</div>
</div>
<script type="text/javascript">
$(document).height();
$('.backdrop').height($(document).height());
$(document).ready(function(){
$('.smllpic img').hover(function () {
var $this = $(this);
$this.stop().animate({'opacity':'1.0'},200);
},function () {
var $this = $(this);
$this.stop().animate({'opacity':'0.7'},200);
});});
$(window).bind("load", function() {
var preload = new Array();
$(".box").each(function() {
s = $(this).attr("src").replace(/\.(.+)$/i, "_on.$1");
preload.push(s)
});
var img = document.createElement('img');
$(img).bind('load', function() {
if(preload[0]) {
this.src = preload.shift();
}
}).trigger('load');
});
$(document).ready(function(){
function centreit(){
//get the height and width of the modal
var modal_height = $('.box').height();
var modal_width = $('.box').width();
//get the height and width of the page
var window_width = $(window).width();
var window_height = $(window).height();
//calculate top and left offset needed for centering
var topp = (window_height - modal_height)/2;
var left = (window_width - modal_width)/2;
//apply new top and left css values
$('.box').css({'top' : topp+'px' , 'left' : left+'px', 'right': left+'px','bottom':topp+'px'}); };
$('.lightbox').click(function(e) {
e.preventDefault(); // keeps new page from loading
var thisPicture = $(this).attr('href'); // path to full sized picture,
function getit(){
$('body').append('<div class="backdrop" label="click to close"></div><div class="box" id="centre" ><div class="close">x</div><div style="cursor:pointer; opacity:1;font-family:Agency FB;margin-top:50%; right:-20px;position:fixed;color:white;font-size:50px; z-index:50;-webkit-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;-moz-box-shadow:0px 0px 5px #444444;-webkit-box-shadow:0px 0px 5px #444444;box-shadow:0px 0px 5px #444444;">></div><div style="cursor:pointer; opacity:.35;font-family:Agency FB;margin-top:50%; left:-20px; position:absolute; font-size:50px;color:white; z-index:70;-webkit-border-radius:5px;-moz-border-radius: 5px; border-radius:5px;-moz-box-shadow:0px 0px 5px #444444; -webkit-box-shadow:0px 0px 5px #444444; box-shadow:0px 0px 5px #444444;"><</div><img class="motown" src="'+thisPicture+'" style="max-height:705px;max-width:905px;z-index:50;"/></div>');
};
$(window).resize(function(){
$('.box').resize();
$('.motown').resize();
centreit();
});
getit();
centreit();
$("html").css("overflow", "hidden");
$('.backdrop').fadeTo(500,0.9);
$('.box').children().fadeIn(1000);
//$('.backdrop').css({ 'display' : 'block', opacity : 0});
$('.close').click(function(){
close_box();});
$('.backdrop').click(function(){
close_box();});
function close_box(){
$('.backdrop').remove();
$('.box').remove();
$("html").css("overflow", "");};
});});
</script>
</body>
</html>
You should try:
margin: 0 auto 0;
left: 0;
right: 0;
To fix the centering. So that would leave you with:
.box
{
margin:0 auto 0;
left: 0;
right: 0;
clear:both;
position:fixed;
max-height:705px;
max-width:905px;
background:black;
z-index:52;
padding:0px;
border:black 1.2px solid;
overflow:hidden;
}