How to upload and save multiple photo in database - php

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.

Related

Ajax file Upload giving the undefined index file from the php side

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.

decode base64 image on php get blank image

I'm trying to decode base64 image on php but i get blank image with black screen showing that windows doesn't support this type of file.
Here is my code
public function uploadfoto(){
$img = $_POST['foto'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$filedir = "./assets/upload/presensi/mx_" . mktime() . ".jpg";
$filename = "mx_".mktime().".jpg";
$result = file_put_contents($filedir, $data);
}
I get the image from my webcam and here is my view
<form id ="inputfoto">
<div id="my_camera" style="width: 320px; height: 240px;" class="center"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="<?php echo base_url();?>assets/dist/js/webcamjs/webcam.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 100
});
Webcam.attach( '#my_camera' );
</script>
<div id="results" align = "middle" >Hasil akan tampil di sini</div>
<input type="button" value="Take Snapshot" onclick="take_snapshot()" class="center" style="margin-bottom: 5px;">
<input type="button" value="Submit" onClick="saveSnap()" class="center">
</form>
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>HASIL</h2>' +
'<img id="foto" src="'+data_uri+'"/>';
} );
}
function saveSnap(){
var file = document.getElementById("foto").src;
var formdata = new FormData();
formdata.append("foto", file);
var ajax = new XMLHttpRequest();
ajax.open("POST", "<?php echo base_url();?>asisten/presensi/uploadfoto");
ajax.send(formdata);
}
</script>
And here is the
Blank Image
What's wrong with my code? Thank you very much for your respond.
This code works for me.Please check it
$image = $this->generateImage($_POST['foto']);
public function generateImage($img)
{
$folderPath = "uploads/";
$image_parts = explode(";base64,", $img);
$image_type_aux = explode("uploads/", $image_parts[0]);
$image_base64 = base64_decode($image_parts[1]);
$name = uniqid() . '.png';
$file = $folderPath . $name;
file_put_contents($file, $image_base64);
return $name;
}

JQuery For Download Button

I am working on a project which is cropping uploaded image in circle and then save it for preview. Here is also a button for download saved image which is cropped.
Here is my main php page:
<html lang="en">
<head>
<title>PHP - jquery ajax crop image before upload using croppie plugins</title>
<script src="http://demo.itsolutionstuff.com/plugin/jquery.js"></script>
<script src="http://demo.itsolutionstuff.com/plugin/croppie.js"></script>
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/bootstrap-3.min.css">
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/croppie.css">
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Image Cropping Area</div>
<div class="panel-body">
<div class="row">
<div class="col-md-4 text-center">
<div id="upload-demo" style="width:350px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<strong>Select Image:</strong>
<br/>
<input type="file" id="upload">
<br/>
<button class="btn btn-success upload-result">Upload Image</button>
</div>
<div class="col-md-4" style="">
<div id="upload-demo-i" style="background:#e1e1e1;width:300px;padding:30px;height:300px;margin-top:30px"></div>
</div>
<div>
<a name="Download Save Image" id="download" download>Download Save Image</a>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$uploadCrop = $('#upload-demo').croppie({
enableExif: true,
viewport: {
width: 200,
height: 200,
type: 'circle'
},
boundary: {
width: 300,
height: 300
}
});
$('#upload').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "ajaxpro.php",
type: "POST",
data: {"image":resp},
success: function (data) {
console.log(data);
var response = JSON.parse(data);
if (response.image) {
html = '<img id="preview" src="' + response.image + '" />';
$("#upload-demo-i").html(html);
$('#download').attr({
target: '_blank',
href: response.image
})
}else {
alert('Failed to upload image');
}
}
});
});
});
</script>
</body>
</html>
and the other for ajax is:
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
if (file_put_contents('upload/' . $imageName, $data)) {
echo json_encode(['image' => 'upload/' . $imageName]); // upload is successful and we return image URL to Javascript
}else {
echo json_encode(['image' => false]); // if upload fails
}
Its functionality is simple and working well.I tried hard to make a simple downloadable button but never found suitable JQuery. Now I am looking for JQuery for my download button to download cropped image. Kindly guide me what part of code I have to put and where.
Thanks for the help. :)
I have changed your Download image button to <a> and given it an id of download and used HTML5 download attribute to force file download
<div>
<a name="Download Save Image" id="download" download>Download Save Image</a>
</div>
Your PHP
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
if (file_put_contents('upload/' . $imageName, $data)) {
echo json_encode(['image' => 'upload/' . $imageName]); // upload is successful and we return image URL to Javascript
}else {
echo json_encode(['image' => false]); // if upload fails
}
Then in your AJAX get the image URL and set it to the download anchor tag by adding the href and target attributes.
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "ajaxpro.php",
type: "POST",
data: {"image": resp},
success: function (data) {
console.log(data);
var response = JSON.parse(data);
if (response.image) {
html = '<img id="preview" src="' + response.image + '" />';
$("#upload-demo-i").html(html);
$('#download').attr({
target: '_blank',
href: response.image
})
}else {
alert('Failed to upload image');
}
}
});
});
});

Load the Images using jquery File Api

We are using jquery.fileApi.js to upload images in a form alongwith Yii Framework. https://rubaxa.github.io/jquery.fileapi/
We have successfully uploaded the images on the server.
Here's the code to upload a file,
<script>
var examples = [];
var imageNames = [];
</script>
<div id="multiupload">
<form class="b-upload b-upload_multi" action="<?php echo $this->createUrl('item/sellNow') ?>" method="POST" enctype="multipart/form-data">
<div class="whiteBox clearfix" id="mulUplImgParent" style="display: none;">
<ul id="sortable" class="js-files b-upload__files">
<li class="col-xs-6 col-sm-2 col-md-2 js-file-tpl b-thumb" data-id="<%=uid%>" title="<%-name%>, <%-sizeText%>">
<header class="clearfix">
<div data-fileapi="file.remove" class="b-thumb__del pull-left"></div>
<% if( /^image/.test(type) ){ %>
<div data-fileapi="file.rotate.cw" class="b-thumb__rotate pull-right"></div>
<% } %>
</header>
<div class="b-thumb__preview">
<div class="b-thumb__preview__pic"></div>
</div>
</li>
</ul>
</div>
<div class="form-group">
<div id="uploadMulImgBtn" class="btn btn-pink btn-small js-fileapi-wrapper">
<span>Browse Images</span>
<input type="file" name="filedata" />
</div>
<figure class="note"><strong>Hint:</strong> You can upload all images at once!</figure>
</div>
</form>
<script type="text/javascript">
examples.push(function() {
$('#multiupload').fileapi({
multiple: true,
url: '<?php echo $this->createUrl('item/uploadImage') ?>',
paramName: 'filedata',
duplicate: false,
autoUpload: true,
onFileUpload: function(event, data) {
imageNames.push(data.file.name);
$("#item-images").val(imageNames.join(','));
},
onFileRemoveCompleted: function(event, data) {
var removeItem = data.name;
imageNames = jQuery.grep(imageNames, function(value) {
return value != removeItem;
});
$("#item-images").val(imageNames.join(','));
},
elements: {
ctrl: {upload: '.js-upload'},
empty: {show: '.b-upload__hint'},
emptyQueue: {hide: '.js-upload'},
list: '.js-files',
file: {
tpl: '.js-file-tpl',
preview: {
el: '.b-thumb__preview',
width: 80,
height: 80
},
upload: {show: '.progress', hide: '.b-thumb__rotate'},
complete: {hide: '.progress'},
progress: '.progress .bar'
}
}
});
});
</script>
</div>
Server Side Code
public function actionUploadImage(){
$userId = Yii::app()->user->id;
$tmpFilePath = $_FILES['filedata']['tmp_name'];
$imageName = $_FILES['filedata']['name'];
$path = 'user_files/';
if(is_dir($path))
{
$dir = $path.$userId;
if(!is_dir($dir))
{
mkdir($dir,0777);
}
$subDir = $dir . '/temp';
if(!is_dir($subDir))
{
mkdir($subDir,0777);
}
$imagePath = "$subDir/$imageName";
move_uploaded_file($tmpFilePath, "$subDir/$imageName");
$image = new Image($imagePath);
$image->resize(190, 190);
$image->save();
$jsonResponse = array('imageName' => $imageName,'imagePath' => $imagePath);
echo CJSON::encode($jsonResponse);
}
//var_dump($_FILES);
//var_dump($_POST);die;
}
We are having issues how to load those images again on the form.
We want to show uploaded images on edit form along with all the event handlers bind through jquery.fileApi .
We cant figure out a way which could render already uploaded images.
Thanks,
Faisal Nasir

add progress bar to jquery ajax file upload

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/.

Categories