hey there i am using ajax to upload images. the codes are as follows.
index.php
<html>
<head>
</head>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.wallform.js"></script>
<script>
$(document).ready(function() {
$('#photoimg').die('click').live('change', function() {
//$("#preview").html('');
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
console.log('ttest');
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
console.log('test');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
console.log('xtest');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
});
});
</script>
<style>
body
{
font-family:arial;
}
#preview
{
color:#cc0000;
font-size:12px
}
.imgList
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;
float:left;
}
</style>
<body>
<div>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
<h1>Upload your images</h1>
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimg" multiple />
</div>
</form>
</div>
</body>
</html>
the ajaxImageUpload.php
<?php
error_reporting(0);
session_start();
$session_id='1'; //$session id
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname);
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
}
}
echo $uploaddir.$image_name;
?>
right now it displays an animated gif while it uploads the images. what i want to do is remove the gif and replace it with a progress bar but i have no clue how to do this and i am on a time schedule. could anyone please tell me how to do this. thanks!
The PHP code for processing the upload does not run until the entire file is uploaded, so it is not possible for you detect how much of the file has been uploaded in that script.
Generally you find upload progress bars built into a browser or some "client-side" program like a Flash application that can control that level of transfer.
For a strict PHP and Javascript implementation there are some workarounds that are fragile and a lot of work and are not very common (hence why you are asking here). There are some jQuery plugins that exist that can do this http://plugins.jquery.com/uploadfile/.
Related
I had look to the similar question and its doesn't solve my problem
I want to create file multiple upload system with progressbar using php
and i have this error
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.<anonymous>
my code is
<?php
error_reporting(0);
$state="white";
$count=0;
if(isset($_GET["state"])){
$state=$_GET["state"];
$count=$_GET["count"];
}
?>
<html >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="كتابك القريب,أدهم شرقاوي,روايات, كتب pdf,تحميل كتب,كتب دراسية,pdf,books">
<meta name="google-site-verification" content="ieyWI-BKgki1_LGBMFqdFYkGyEeHlMSEAodDuxKcN7A" />
<link rel="stylesheet" href="controls.css">
<!--
-->
<style>
.bar
{
position: absolute;
height: 15px;
background-color: rgb(27, 26, 26);
box-shadow:inset 1px 1px 1px 1px #fff5;
width: 80%;
bottom: 45px;
border-radius:15px ;
}
.pbar
{
position: absolute;
height: 15px;
background-color:#941ab4;
width: 0;
border-radius:15px ;
}
</style>
<title>كتابك القريب</title>
<script src="jquery.js"></script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
var Vcount= <?php echo $count; ?>;
if (state=="succsses") {$(document).ready(function() { $(".succsses").css("display","block");}); }
</script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
if (state=="error") { $(document).ready(function() { $(".error").css("display","block"); }); }
</script>
<script>
$(document).ready(function() {
$(".x").click(function() {
$(".succsses").css("display","none");
});
});
$(document).ready(function() {
$(".x").click(function() {
$(".error").css("display","none");
});
});
</script>
</head>
<body>
<div class="succsses" id="succsses" >
<p><?php if ($state=="succsses") { echo"تم تحميل ($count) ملفات بنجاح" ;}?></p>
<span class="x">x</span>
</div>
<div class="error" id="error" >
<p><?php if ($state=="error") { echo"فشل التحميل " ;}?></p>
<span class="x">x</span>
</div>
<div class="login-form">
<img src="https://yourclosebook.com/res/logos/ryhan.png" alt="" class="ava">
<form action="upload.php" method="post" enctype="multipart/form-data" id="frm">
<input type="email" name="email" id="" placeholder="email (اختياري)">
<input type="file" name="file[]" id="costum-file" accept="application/pdf,application/msword,.docx" multiple >
<input type="submit" value="تحميل" id="upload">
</form>
<div class="bar">
<span class="pbar" id="pb"></span> <span class="ptext " id="pt"></span>
</div>
<P> (*.pdf,*.docx,*.doc,*.ppt,*pptx)يمكنكم تحميل ملفات من الصيغ المدرجة جانبا</P>
<h3 id="friend"> <a href="https://www.yourclosebook.com" target="_blank" > كتابك القريب !</a> صديقك المقرب</h3>
</div>
<style>
</style>
<script src="upload.js"></script>
<script>
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
</body>
</html>
uploade.php
<?php
require_once("conn.php");
header("Content-Type:application/json");
$err="";
$UPLOADED=NULL;
$count=0;
$i=0;
$succeded=[];
$faild=[];
for ($i; $i <count($_FILES['file']['name']) ; $i++) {
$target_path="uploads/";
$file=$_FILES['file']['name'][$i];
$file_temp=$_FILES['file']['tmp_name'][$i];
$fileSize =$_FILES['file']['size'][$i];
$fileError =$_FILES['file']['error'][$i];
$fileType =$_FILES['file']['type'][$i];
$fileEXT =explode('.',$file);
$fileRealExt=strtolower(end($fileEXT));
$target_path= $target_path.$file;
$allowed =array('pdf','doc','docx');
if (!empty($file)) {
if (in_array($fileRealExt,$allowed)) {
if ($fileError===0) {
$helpTimes=1;
$email=$_POST['email'];
$email= $db->real_escape_string($email);
$file= $db->real_escape_string($file);
$UPLOADED=move_uploaded_file($file_temp,$target_path);
if ($UPLOADED) {
$insert = $db->query("INSERT INTO user_uploads(email,filepath,upload_time,help_times) VALUES('".$email."','".$file."',NOW(),'".$helpTimes."')");
$count=$i+1;
$succeded=array(
'name'=>$name,
'file'=>$file
);
}else{
$faild= array('name' => $name);
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
$err= "حدث خطأ غير متوقع";
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
echo header("Location:index.php?state=error&error=notAcceptedFileFormat");
}
}else{
$err=" يجب اختيار ملف واحد على الاقل";
echo header("Location:index.php?state=error&error=empty");
}
// --------------------
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
}
}
echo $err;
if ($count>0) {
//index.php
echo header("Location:index.php?state=succsses&count=$count");
if (!empty($_POST['email'])) {
$email=$_POST['email'];
$from = "MIME-Version: 1.0" . "\r\n";
$from .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$from .= 'From: YOUR CLOSE BOOK TEAM <contact#yourclosebook.com>' . "\r\n";
$s=" رسالة شكر";
$messagge="<H1>باسمنا نحن فريق موقع كتابك القريب نقد لكم فائق الشكر لاجل مساعدتنا بتقديم كتبكم الثمينة</H1>";
$mail= mail($email,$s,$messagge,$from);
if (!$mail) {
echo"email sending error";
}
else{
echo"check your email";
}
}
}else{
echo header("Location:index.php?state=error");
}
upload.js
var app=app ||{};
(function(o){
"use strict";
var ajax,getFormData,setProgress;
ajax =function (data)
{
var xhr= new XMLHttpRequest(),uploaded;
xhr.addEventListener('readystatechange',function()
{
//readyState===4 => done
if (this.readyState===4)
{
/*
status===200=> ok*/
if (this.status===200)
{
uploaded= JSON.parse(this.response);
if (typeof o.options.finished==='function')
{
o.options.finished(uploaded);
}
}
else
{
if (typeof o.options.error==='function')
{
o.options.error();
}
}
}
});
xhr.upload.addEventListener('progress',function(event)
{
var percent;//%
if (event.lengthComputable===true)
{
percent= Math.round((event.loaded/event.total)/100);
setProgress(percent);
}
});
xhr.open('post',o.options.processor);
xhr.send(data);
};
getFormData =function (source) {
var data = new FormData(),i;
for ( i = 0; i < source.length; i++) {
data.append('costum-file[]',source[i]);
}
data.append('ajax',true);
return data;
};
setProgress =function (value) {
if (o.options.porgressBar !== undefined) {
o.options.porgressBar.style.width=value?value+'%':0;
}
};
o.uploader=function (options) {
o.options=options;
if (o.options.files!==undefined) {
ajax(getFormData(o.options.files.files));
}
}
}(app));
There are some issues with your code:
In your main file you have an email element but in your upload.js file you are not adding it to your FormDara object. So in your uploade.php file you don't have access to it and $email=$_POST['email']; will throw an error
In your upload.js you are naming your file objects costum-file fun in your upload.php you are looking for file objects with the name of file. These two should have same name.
echo header("Location:index.php"); is incorrect and you should only use header("Location:index.php");
If you are calling upload.php file via ajax request then you can not do php redirect(header("Location:index.php");). What you should do is to return some json response and then pars it in your main file JavaScript and show relevant messages(Error or success)
So to sum them up what you need to change to fix the error you are getting is(I'm just highlighting the changes and not the whole code):
main(index.php?) file
You need to provide an id for the email element:
<input type="email" name="email" id="email" placeholder="email (اختياري)">
You need to add this email element to your JavaScript call
<script type="text/javascript">
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
var eml = document.getElementById('email');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
email:eml,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
upload.js
You need to change the file element to file and also add the email element in the FormData object
getFormData =function (source) {
var data = new FormData(), i;
for ( i = 0; i < source.length; i++) {
data.append('file[]',source[i]);
}
data.append('email', o.options.email.value);
data.append('ajax', true);
return data;
};
And finally in your upload.php file change all the echo header("Location:index.php") instances with a json encoded string like what you have here:
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
With proper response which then you can parse in your index.php file.
Please give it a try and see if it fixes your issue.
I've tried everything i came across and i am sure there is something i dont have in the code .Please i need some help thks.
This is the html which is a form with one input which should receive the file
<div id="Posts">
<h1 style="text-align: center;color: red;">SERVICES</h1>
<p style="text-align: center;"><span style="color:red;">***</span> please ensure to look at the definitions of every field... <span style="color:red;">***</span></p>
<form id="promo_imgs" enctype="multipart/formdata">
<h5 style="text-align: center;"> About the Services You offer</h5><hr style="width: 30%; border:0.5px dashed red;">
<div id="imgpr" class="imgpromo" style="max-width: 40%; min-height: 60px;border:dashed 0.5px;">
<label for="promotion" class="btn btn-primary">
Select an Image
</label>
<img src="" alt="" width="100%" style="max-height: 250px;" id="img">
<input type="file" name="promo0" accept=".png, .jpeg, .jpg" id="promotion" style="display:none;">
</div>
<button class="btn btn-primary" type="submit" id="serv_upload" name="serv_upload">Upload</button>
</form><span id="ajax">
<!--upload an image -->
</span>
then this is the jquery part of it which should preview the image (which works) and then upload the image(which goes successfully to return an undefined index file error)
/* to preview before upload service images*/
$(document).on('change',"#promotion",function(){
var link =URL.createObjectURL(event.target.files[0]);
console.log(link);
var $this=$(this);
$("#img").slideDown("fast").attr('src',link);
$("#serv_upload").slideDown("slow");
});
/* to upload service images*/
$(document).on('click',"#serv_upload",function(e){
e.preventDefault();
$("#ajax").html("Uploading...");
var files = $('#promotion').val(e.target.files);
for (var i = 0; i < files.length; i++) {
var file = files[i];
var formdata= new FormData();
formdata.append('file',file);
$("#ajax").append(file.name);
$.ajax({
type:"POST",
url:"aboutinsert.php",
data:{formdata:formdata},
processData:false,
contentType:false,
cache:false,
success: function(data){
$("#ajax").html(data);
}
});
}
});
Finally the php part
$dir="img/portfolio" ;
$file = $_FILES['file']['name'];
$path = $dir.basename($file);
$ext= pathinfo($path,PATHINFO_EXTENSION);
$extensions = array("JPG","jpg","jpeg","png");
$exts=strtolower($ext);
if (!in_array($exts, $extensions)) {
# code...
echo "sorry you donot have the right file format";
}
elseif ($_FILES['file']['size']>2000000) {
# code...
echo "your file is larger than 2mb";
}
elseif (file_exists($path)) {
# code...
echo "sorry a file already exists with this name change the name and try again";
}
else{
if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
# code...
echo basename($_FILES['file']['name']). "upload success";
}
else{
echo "file Upload failed";
}
}
There seem to be some random names being used in the $_FILES array in your PHP code. You use:
$file = $_FILES['file']['name'];
and then
elseif ($_FILES['promo0']['size']>2000000) {
and finally
if (move_uploaded_file($_FILES['image']['tmp_name'], $path)) {
Which is it? If you're not certain, you could var_dump($_FILES); and see what you have.
I'm trying to make it where it where when an image is uploaded it will compress the image into a smaller size than what it currently is or something like that. I have it where an admin is able to upload an image or images to the main page slider, but i'm wanting to make it where it's a smaller size of the image instead of the full 1.1mb image or what not. Any Ideas on how I can currently do this with my code?
Heres my Slider Code where it gets the link of where the image is from my DB:
<div class="tp-banner-container rev_slider_wrapper fullwidthbanner-container"
data-alias="news-hero72">
<div class="tp-banner-slider">
<ul>
<?php
$stmt = $DB_con->prepare('SELECT * FROM slider');
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<li data-index="rs-80" data-transition="fade" data-slotamount="7" data-masterspeed="500"
data-saveperformance="on"
data-title="Intro Slide">
<img src="images/slider/<?php echo $row['link']; ?>" alt="slidebg1"
data-bgposition="center top" data-bgfit="cover"
data-bgrepeat="no-repeat">
<div class="revolution_heading_font tp-caption grey_heavy_72 skewfromrightshort tp-resizeme rs-parallaxlevel-2" data-x="0"
data-y="200" data-speed="700" data-start="10" data-easing="Power3.easeInOut" data-splitin="chars"
data-splitout="none" data-elementdelay="0.1" data-endelementdelay="0.1"
style="z-index: 5; max-width: inherit; max-height: inherit; white-space: nowrap;color: #FFFFFF;font-size:30pt;font-family: Montserrat">
<?php echo $row['slide_name']; ?>
</div>
<div class="revolution_font tp-caption grey_heavy_72 skewfromrightshort tp-resizeme rs-parallaxlevel-2" data-x="5"
data-y="300" data-speed="300" data-start="600" data-easing="Power3.easeInOut" data-splitin="words"
data-splitout="none" data-elementdelay="0.1" data-endelementdelay="0.1"
style="z-index: 5; max-width: inherit; max-height: inherit; white-space: nowrap;color: #ffffff;font-weight: 300;font-size:18pt; line-height: 30pt; margin-left:8px">
<?php echo $row['slide_desc'];?>
</div>
<?php
}
}
else
{
?>
<?php
}
?>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
Here's my PHP Where the admin is able to edit the slider name, description and upload slider images.
<?php
if(isset($_GET['edit_id']) && !empty($_GET['edit_id']))
{
$id = $_GET['edit_id'];
$stmt_edit = $DB_con->prepare('SELECT * FROM sponsors WHERE id =:uid');
$stmt_edit->execute(array(':uid'=>$id));
$edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
extract($edit_row);
}
else
{
header("Location: ../../login.php");
}
if(isset($_POST['btn_save_updates']))
{
$username = $_POST['user_name'];
$description = $_POST['description'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if($imgFile)
{
$upload_dir = '../images/sponsors/';
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userprofile = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 5000000)
{
unlink($upload_dir.$edit_row['logo']);
move_uploaded_file($tmp_dir,$upload_dir.$userprofile);
}
else
{
$errMSG = "Sorry, Your File Is Too Large To Upload. It Should Be Less Than 5MB.";
}
}
else
{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF Extension Files Are Allowed.";
}
}
else
{
$userprofile = $edit_row['logo'];
}
if(!isset($errMSG))
{
$sponsorname = $_POST['sponsor_name'];
$motto = $_POST['sponsor_motto'];
$phone = $_POST['sponsor_phone'];
$website = $_POST['sponsor_website'];
$son = $_POST['sponsor_on'];
$stmt = $DB_con->prepare('UPDATE sponsors SET name=:sname, motto=:smotto, phone=:sphone,website=:swebsite,live=:son, logo=:upic WHERE id=:uid');
$stmt->bindParam(':sname',$sponsorname);
$stmt->bindParam(':smotto',$motto);
$stmt->bindParam(':sphone',$phone);
$stmt->bindParam(':swebsite',$website);
$stmt->bindParam(':son',$son);
$stmt->bindParam(':upic',$userprofile);
$stmt->bindParam(':uid',$id);
if($stmt->execute()){
?>
<script>
alert('Successfully Updated...');
window.location.href='managesponsors.php?action=sponsorupdated';
</script>
<?php
}
else{
$errMSG = "Sorry User Could Not Be Updated!";
}
}
}
?>
If what you want is to compress the uploaded image file then the straight forward way is to use php function imagejpeg() and edit your upload code
from this:
move_uploaded_file($tmp_dir,$upload_dir.$userprofile);
to this:
if (move_uploaded_file($tmp_dir,$upload_dir.$userprofile)) {
$image = imagecreatefromjpeg($upload_dir.$userprofile);
imagejpeg($image,$upload_dir.$userprofile,75); //75 is quality of the compression (can be anywhere lower than 100)
}
Now your image should be 75% of the original size, do note that this only works for jpeg images, you will need to replace imagecreatefromjpeg with imagecreatefromgif and imagecreatefrompng depending on the uploaded image format
you could use either GD or Imagick to accomplish this like below
$thumb = new Imagick('myimage.gif');
$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
$thumb->destroy();
image resize using imagick
or you will get plenty of PHP libraries for the same which will ease your job.
Please help me....
I want to upload up to 5 photos and save in database.
I want by selecting photo it will upload automatically and then the selected photo will appear in the page.
It will occure with one by one photo, up to 5 photos and the photos can be seen in the page.
Then if i submit it, it will save the photos (not the photo link) in a table named user in my database named my_db
<?php
include('dbcon.php');
session_start();
$session_id='1'; //$session id
?>
<html>
<head>
<title>Ajax Image Upload 9lessons blog</title>
</head>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.wallform.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').die('click').live('change', function() {
//$("#preview").html('');
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
console.log('v');
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
console.log('z');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
console.log('d');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
});
});
</script>
<style>
body
{
font-family:arial;
}
.preview
{
width:200px;
border:solid 1px #dedede;
padding:10px;
}
#preview
{
color:#cc0000;
font-size:12px
}
</style>
<body>
<div style="width:600px">
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />
</div>
</form>
</div>
</body>
</html>
And here ajaximage.php
<?php
include('dbcon.php');
session_start();
$session_id='1'; //$session id
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$sql="INSERT INTO user (image, uid)
VALUES
('$actual_image_name','$session_id')";
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
There is a very good tutorial on how to do this using dropzone.js here http://www.infotuts.com/drag-drop-multiple-file-upload-with-dropzone-save-to-database/
Their php:
</p>
<?php
include 'db.php';
$upload_dir = 'myuploads';
function insert_data($ar){
$obj=new DB();
$key="(f_name , f_size, f_link,f_type,d_date)";
$val="('{$ar['fname']}', '{$ar['fsize']}','{$ar['flink']}','{$ar['ftype']}','{$ar['fdate']}')";
mysqli_query($obj->connection(),"INSERT INTO file_upload ".$key." VALUES ".$val);
//mysqli_close($obj->con);
}
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
// using DIRECTORY_SEPARATOR constant is a good practice, it makes your code portable.
$targetPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
// Adding timestamp with image's name so that files with same name can be uploaded easily.
$fname = $targetPath.time().'-'. $_FILES['file']['name'];
$file_name=time().'-'. $_FILES['file']['name'];
$ftype=$_FILES["file"]["type"];
$fsize=($_FILES["file"]["size"] / 1024);
$tmpname=$_FILES["file"]["tmp_name"];
// Change $flink path to your folder where you want to upload images.
$flink='http://localhost/dragdrop%20file%20upload/myuploads/'.$file_name;
$arr= array('fname'=>$file_name,
'fsize'=>$fsize,
'flink'=>$flink,
'ftype'=>$ftype,
'fdate'=>date('Y-m-d h:i:s'));
insert_data($arr);
move_uploaded_file($tempFile,$fname);
}
?>
<p style="text-align: justify;">
Their html
<head>
<script src="./path/to/dropzone.js"></script>
</head>
<body>
<div id="main">
<p> Drag n Drop Your image files below - <b>InfoTuts</b></p>
</div>
<form action="file-upload.php" class="dropzone"></form>
</body>
My "Invoke Dropzone with some useful parameters"
var myNewDropzone = new Dropzone("#newuploadedForm", {
//Prepare the drop zone area
url: "<?php echo get_bloginfo('url'); ?>/path-to/your-ajax-file.php",
method: "POST",
uploadMultiple: true,
autoProcessQueue: false, /* Make this true if you don't want to handle the requests in your own Javascript - much easier! */
addRemoveLinks: false, /* Make true to let Dropzone handle remove document clicks */
clickable: true,
maxFiles: 10,
parallelUploads: 10,
maxFilesize: 50,
acceptedFiles:"image/png,image/gif,image/jpeg,application/pdf", /* change as needed and update the dictInvalidFileType below */
dictInvalidFileType: "Sorry, we only support .PNG, .JPG, .GIF, and .PDF files currently",
previewTemplate: document.querySelector('#preview-template').innerHTML, /* Remove this unless you create a preview template */
dictMaxFilesExceeded: "Sorry, you can upload a maximum of 10 images as pages. Please convert your images to one PDF document.",
/* Below is a commented out example of building your own client size file handler
init : function() {
this.on("addedfile", function(file) { new_file_added(file); });
//this.on("sending", function(file, xhr, formData) { sending_file(file, xhr, formData); });
this.on("thumbnail", function(file,fileurl) { new_thumbnail_added(file); });
this.on("removedfile", function(file) { new_file_removed(file); });
this.on("totaluploadprogress", function(progress) { display_progress(progress); });
this.on("queuecomplete", function() { all_files_uploaded(); });
//this.on("processing", function(file) { new_file_processed(file); });
} */
});
I think you will find dropzone works really well, and allows you do it the easy way (let dropzone take control) or slightly harder but you get full control of the upload process
If you want upload multiple photos to php server and save it in db.
First, you should dynamic add more input file element in front page, then in your ajaximage.php, check this reserved.variables.files, got everything you need to complete your task.
I believe I have most everything correctly configured for the recorder because I can
1 - Get the Flash permission prompt
2 - Start recording
3 - Listen to the playback
but when I go to save the file I can find it neither in the upload directory nor the temp dir.
I know php is working because I have tested a post - upload form successfully.
Here's the html and php:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My Recorder</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js'></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/recorder.js"></script>
<script type="text/javascript">
$(function() {
var appWidth = 24;
var appHeight = 24;
var flashvars = {'event_handler': 'microphone_recorder_events', 'upload_image': 'images/upload.png'};
var params = {};
var attributes = {'id': "recorderApp", 'name': "recorderApp"};
swfobject.embedSWF("recorder.swf", "flashcontent", appWidth, appHeight, "10.1.0", "", flashvars, params, attributes);
});
</script>
<style>
#control_panel { white-space: nowrap; }
#control_panel a { outline: none; display: inline-block; width: 24px; height: 24px; }
#control_panel a img { border: 0; }
#save_button { position: absolute; padding: 0; margin: 0; }
#play_button { display: inline-block; }
</style>
</head>
<body>
<div id="status">
Recorder Status...
</div>
<div id="control_panel">
<a id="record_button" onclick="Recorder.record('audio', 'audio.wav');" href="javascript:void(0);" title="Record"><img src="images/record.png" width="24" height="24" alt="Record"/></a>
<span id="save_button">
<span id="flashcontent">
<p>JavaScript enabled and Adobe Flash Player installed, please</p>
</span>
</span>
<a id="play_button" style="display:none;" onclick="Recorder.playBack('audio');" href="javascript:void(0);" title="Play"><img src="images/play.png" width="24" height="24" alt="Play"/></a>
</div>
<div id="upload_status">
</div>
<form id="uploadForm" name="uploadForm">
<input name="authenticity_token" value="xxxxx" type="hidden">
<input name="upload_file[parent_id]" value="1" type="hidden">
<input name="format" value="json" type="hidden">
</form>
</body>
</html>
<?php
$save_folder = dirname(__FILE__) . "/audio";
if(! file_exists($save_folder)) {
if(! mkdir($save_folder)) {
die("failed to create save folder $save_folder");
}
}
function valid_wav_file($file) {
$handle = fopen($file, 'r');
$header = fread($handle, 4);
list($chunk_size) = array_values(unpack('V', fread($handle, 4)));
$format = fread($handle, 4);
fclose($handle);
return $header == 'RIFF' && $format == 'WAVE' && $chunk_size == (filesize($file) - 8);
}
$key = 'filename';
$tmp_name = $_FILES["upload_file"]["tmp_name"][$key];
$upload_name = $_FILES["upload_file"]["name"][$key];
$type = $_FILES["upload_file"]["type"][$key];
$filename = "$save_folder/$upload_name";
$saved = 0;
if($type == 'audio/x-wav' && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) && valid_wav_file($tmp_name)) {
$saved = move_uploaded_file($tmp_name, $filename) ? 1 : 0;
}
if($_POST['format'] == 'json') {
header('Content-type: application/json');
print "{\"saved\":$saved}";
} else {
print $saved ? "Saved" : 'Not saved';
}
exit;
?>
btw - this came straight from the cykod site, I've done barely anything to it...
also, how do i convert to mp3 upon pressing the save button?
Thanks!
Don't know if you ever got an answer to this, but check your folder permissions. After setting my "audio" folder such that everyone can read/write it worked. Of course this is not the best way to do this - you need to set your apache/php account to be writeable to the folder - but at least this should get you going.