upload div image to database on submit - javascript

I have been trying to get an answer on how to upload an image that was created from a div. i have the code to create the div to an image now I need to know how I can upload that image to my database folder I need to upload it on submit with a unique file name. the one that concerns me the most is how to upload on submit. Will it be possible to upload the image of div using the same code to upload regular image files?
$(document).ready(function(){
var element = $("#firstshirt"); // global variable
var getCanvas; // global variable
$("#btn-Preview-Image").on('click', function () {
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});
$("#btn-Convert-Html2Image").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#btn-Convert-Html2Image").attr("download", "your_pic_name.png").attr("href", newData);
});
});
<center><input id="btn-Preview-Image" type="button" value="Preview"/>
<button type="button" id="btn-Convert-Html2Image" href="#">Download</button>
<br/>
</center>
<center><input type="submit" name="submit" value="Next" /></center>
this is my upload image php
<?php
require_once("configur.php");
$query='UPDATE profile_table SET images="'.$_FILES['file']['name'].'"
WHERE email= "'.$_SESSION['email'].'"';
if ($mysqli->query($query) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$mysqli->close();
?>
<?php
include('configur.php');
if($_POST)
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0)
{
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
// check if file already exit in "images" folder.
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
}
else
{ //move_uploaded_file function will upload your image.
if(move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into profile_table";
if(mysqli_query($link, $query_image))
{
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
else
{
echo'';
}
}
}
}
}
?>

"insert into profile_table" is not valid MySql (or at least wont change anything), I would move
$query='UPDATE profile_table SET images="'.$_FILES['file']['name'].'"
WHERE email= "'.$_SESSION['email'].'"';
to the end under the file has uploaded successfully clause and store its path in the database (change images="'.$_FILES['file']['name'].'" to images="'upload/.$_FILES['file']['name'].'"'). To access the file, you can now query the database and return the stream through another php script.

Related

Auto Uploading file

I've created a website with html and javascript that gets access to your webcam and when users press take photo button a photo is captured. How would I go about directly uploading this to some cloud folder where it is stored?
Thanks
On the page where the button is,:
Create the button which snaps the photo(I don't kbnow how that is done)
<button>Snap photo!</button>
Create a form (invisible form) with the value of anything....anything can be the value just make sure it isn't empty
Use javascript so that when the button is clicked,the form is submitted to a php page
Mke the target of the form be an iframe that you have created so that when they snap the photo,it leads to the same page,without reloading the page]
Here's the code for what I just said:
Snap
</form>
<script>
function rad(){
document.getElementById("crap").submit();
</div>
Make the file handler with this code:
$errors = []; // Store all foreseen and unforseen errors here
$fileExtensions = ['jpeg','jpg','png']; // Get all the file extensions
$fileName = $_FILES['myfile']['name'];
$fileSize = $_FILES['myfile']['size'];
$fileTmpName = $_FILES['myfile']['tmp_name'];
$fileType = $_FILES['myfile']['type'];
$fileExtension = strtolower(end(explode('.',$fileName)));
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
if (isset($_POST['submit'])) {
if (! in_array($fileExtension,$fileExtensions)) {
$errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
}
if ($fileSize > 1000000000) {
$errors[] = "This file is more than 1GB. Sorry, it has to be less than or equal to 1GB";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
echo basename($fileName) ;
} else {
echo "An error occurred somewhere. Try again or contact the admin";
}
} else {
foreach ($errors as $error) {
echo $error . "These are the errors" . "\n";
}
}
}
?>
The only thing is that this uploads the image to your server not a 'cloud folder' ...but it is a folder just place the cloud folder in your webserver then specify the name of the cloud folder in the$uploadDirectory = "/uploads/"; ie change 'uploads' to the name of your cloud folder....
Hopes this helps

Ajax Php Image Upload and Save

I want to upload an image and save it in the uploads folder without refreshing the page. Furthermore, I also want to display the uploaded image on the screen in a div. However, when I run the code, when I try to upload an image, the text continues to say "Image Uploading..." and never finishes to actually upload. Therefore, the image never gets displayed on the page. Additionally, I am having trouble saving my image in the uploads folder, so can someone point me in the right direction? Thank you!
UPDATE: The Ajax POST gets an error each time I try to to upload an image. In fact, the POST request might not even reach my upload.php file. I trie d to alert myself when the request actually reaches upload.php but nothing ever prints out. What may be the potential causes of this?
UPDATE #2: I have included a picture of my file layout. I have the HTML and Javascript in privatecreate.blade.php and the Javascript in upload.php. I want to save the images in uploads folder.
Update #3: I printed out the ajax error and it is "No Input File Specified"
Please bear with my everyone. This is my absolute first time working with php and sql and I am trying my hardest to learn.
HTML:
<div class="container" style="width:700px;">
<br />
<label>Select Image</label>
<input type="file" name="file" id="file" />
<br />
<span id="uploaded_image"></span>
</div>
Javascript:
$(document).ready(function(){
$(document).on('change', '#file', function(){
var name = document.getElementById("file").files[0].name;
var form_data = new FormData();
var ext = name.split('.').pop().toLowerCase();
if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
}
else{
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("file").files[0]);
var f = document.getElementById("file").files[0];
var fsize = f.size||f.fileSize;
if(fsize > 2000000)
{
alert("Image File Size is very big");
}
else
{
form_data.append("file", document.getElementById('file').files[0]);
$.ajax({
url:"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
},
success:function(data)
{
$('#uploaded_image').html(data);
}
,error: function(ts)
{
alert("error:" + ts.responseText);
}
});
}
}
});
});
PHP (upload.php):
<?php
//upload.php
$message = "Running Upload.php";
echo "<script type='text/javascript'>alert('$message');</script>";
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$ext = end($test);
$name = rand(100, 999) . '.' . $ext;
$location = 'uploads/' . $name;
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
}
?>
<?php
//Change your location path
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$ext = end($test);
$name = rand(100, 999) . '.' . $ext;
$location = 'upload/' . $name; // change here & enjoy
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
}
?>

want to change the path of the saving images folder... how to do this

javascript function to call the html2 canvas element to scrrenshot the the target div
<script type="text/javascript">
function capture() {
$('#target').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data (base-64 string)
$('#img_val').val(canvas.toDataURL("image/png"));
//Submit the form manually
document.getElementById("myForm").submit();
}
});
}
</script>
php code
<?php
//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
//Decode the string
$unencodedData=base64_decode($filteredData);
//echo $unencodedData;
//Save the image
$date = date_create();
$timestamp= date_timestamp_get($date);
echo $timestamp;
$rand = mt_rand(100000,999999);
echo $rand;
$string = "cp-string";
echo $string;
$name = "$string.$timestamp.$rand.png";
//$name = "$string/$timestamp/$rand.png";
//$unencodedData = "$string/$timestamp/$rand";
file_put_contents($name , $unencodedData);
?>
Dont know how to give different folders path for saving the image
Normally use copy function for upload file into a folder.
according to your code you can do something like
$dir_to_save = "foldername"
if (!is_dir($dir_to_save)) {
mkdir($dir_to_save);
}
$path = $dir_to_save."/".$name;
file_put_contents($path, $unencodedData);
NOTE: use ABSOLUTE_PATH not relative paths
For more information

How to call a php function from javascript alert

Basically what i am trying to do is- create a page to upload file. Below is the code and its working fine:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function wow_default_alert() {alert("Successfully saved!"); }
</script>
</head>
<body>
<form action="index.php" method="post" name="myForm" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if(isset($_POST["submit"])) {
if (!file_exists('.\\tigerimg\\'))
{
mkdir('.\\tigerimg\\', 0777, true);
}
$target_dir = '.\\tigerimg\\';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
"File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
"File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
echo '<script type="text/javascript">
wow_default_alert();
</script>';
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
But the problem is that if i refresh the page again -after uploading one file successfully, it works with the same post values.
Previously i used the below code to unset post data-which worked for other pages.
clear Code-1
<?php
session_start();
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0)
{
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata']))
{
$_POST = $_SESSION['postdata'];
unset($_SESSION['postdata']);
}
?>
But i cant use it in this one. It shows error:
Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 41
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 47
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\up\index.php on line 47
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 62
So, i tried to also clear the FILES array too by adding 3 lines with the above code.
clear Code-2
<?php
session_start();
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0)
{
$_SESSION['postdata'] = $_POST;
$_SESSION['filedata'] = $_FILES; //new code
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata']))
{
$_POST = $_SESSION['postdata'];
$_FILES = $_SESSION['filedata']; //new
unset($_SESSION['postdata']);
unset($_SESSION['filedata']); //new
}
?>
But now its showing only one error:
Warning: getimagesize(C:\xampp\tmp\php1A2F.tmp): failed to open stream: No such file or directory in C:\xampp\htdocs\up\index.php on line 51.
>>> So, here is one question- why is this happening?
Ok, now i tried another way put the above [clear Code-1] inside a php function function remove_post() and call it just after the code of successful uploading- where i called the alert.
This time its working fine. But now the problem is that the alert doesn't appear. So, is it possible to call the function remove_post() when user clicks the ok in alert.
It looks like you are trying to copy from W3Schools web site, which is not the greatest of places. At any rate, in this instance, I think you may want to do all your processing at the top of your page like so:
<?php
// Not sure if you are storing anything in sessions...
session_start();
// Create a root
define("ROOT_DIR",__DIR__);
// Create a function so you can customize it if you want to
function SaveFileToDisk($dir = '/tigeimg/',$allow = array("image/png","image/jpeg","image/gif"))
{
// Make directory if not exists
if(!is_dir($mkdir = ROOT_DIR.$dir)) {
if(!mkdir($mkdir,0755,true))
return 'mkdir';
}
// Filter filename
$name = preg_replace("/[^0-9a-zA-Z\.\_\-]/","",$_FILES["fileToUpload"]["name"]);
// Assign name
$filename = (!empty($name))? $name : false;
// If empty, record error
if(!$filename)
$error[] = 'nofile';
// Get mime type
$mime = (!empty($_FILES["fileToUpload"]["tmp_name"]))? getimagesize($_FILES["fileToUpload"]["tmp_name"]) : false;
// Record if invalid
if(!$mime)
$error[] = 'invalid';
// Filter out double forward slashes (if user decides to change $dir)
// and adds too many forward slashes
$final = str_replace("//","/",ROOT_DIR."/".$dir."/".$filename);
// If file exists, record error
if(is_file($final))
$error[] = 'exists';
// If too big record error
if($filename > 500000)
$error[] = 'size';
// If not in the allowed file types, record error
if(!in_array($_FILES["fileToUpload"]["type"],$allow))
$error[] = 'type';
// Return array of errors
if(!empty($error))
return $error;
// True or false if no errors are recorded previously
return (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$final));
}
// Just create a simple error returning function
// This is expandable by adding error descriptions stored in database if desired
function ErrorReporting($value = false)
{
$msg['invalid'] = "INVALID File!";
$msg['type'] = "The file you are trying to upload is not a valid image type.";
$msg['exists'] = "The file you are trying to upload is already uploaded.";
$msg['size'] = "The file you are trying to upload is too large.";
$msg['nofile'] = "The file you are trying to upload has no name.";
if($value === true)
return "Successfully uploaded!";
elseif(is_array($value)) {
foreach($value as $error) {
$err[] = (!empty($msg[$error]))? $msg[$error]:"";
}
if(!empty($err))
return implode("",$err);
}
else
return "File failed to upload.";
}
// If post is submitted
if(isset($_POST["submit"]))
// Run the uploader function
$success = SaveFileToDisk();
?><!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
<?php
// if there is an upload, run the js alert
if(isset($success)) {
?>
function error_alert(errmsg)
{
alert(errmsg);
}
error_alert("<?php echo ErrorReporting($success); ?>");
<?php }
?>
</script>
</head>
<body>
<form action="" method="post" name="myForm" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
After user clicks OK for alert you can call the php function as
alert('Your alert');
document.write(' <?php remove_post(); ?> ');
Your remove_post() function will get called after user click OK on alert

why is it that my script only uploads the last image to my ftp and database?

i have a uploading script and works like a charm but i wanted to expand it with not only uploading one image, but several images. That resulted in my script only uploading the last image and not all of them with the text included with them in the textarea. i just can't figure out why it just won't upload all images.
my upload.php:
<?php // Start a session for error reporting session_start(); // Call our connection file require( "includes/conn.php"); // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds
all the valid image MIME types $valid_types=a rray( "image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file[ 'type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that 's easy to read
// I used this function during debugging but it serves no purpose at run time for this example
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
// Set some constants
// This variable is the path to the image folder where all the images are going to be stored
// Note that there is a trailing forward slash
$TARGET_PATH = "content/uploads/";
// Get our POSTed variables
$fname = $_POST['fname '];
$lname = $_POST['lname '];
$image = $_FILES['image '];
// Sanitize our inputs
$fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string(nl2br($lname));
$image['name '] = mysql_real_escape_string($image['name ']);
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH .= $image['name '];
// Make sure all the fields from the form have inputs
if ( $fname == "" || $lname == "" || $image['name '] == "" )
{
$_SESSION['error '] = "All fields are required";
header("Location: indexbackup.php");
exit;
}
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($image))
{
$_SESSION['error '] = "You must upload a jpeg, gif, or bmp";
header("Location: indexupload.php");
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['error '] = "A file with that name already exists";
header("Location: indexupload.php");
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($image['tmp_name '], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql="insert into people (fname, lname, filename) values ('$fname', '$lname', '" . $image[ 'name'] . "')"; $result=m ysql_query($sql)
or die ( "Could not insert data into DB: " . mysql_error()); header( "Location: indexupload.php"); exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod
the directory to be writeable $_SESSION[ 'error']="Could not upload file. Check read/write persmissions on the directory" ; header( "Location: indexupload.php"); exit; } ?>
and this is the page that let's me select the files and fill in the text area:
var abc = 0; // Declaring and defining global increment variable.
$(document).ready(function () {
// To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
$('#add_more').click(function () {
$(this).before($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append($("<input/>", {
name: 'image',
type: 'file',
id: 'file'
}), $("<br/><br/>")));
});
// Following function will executes on change event of file input to select different file.
$('body').on('change', '#file', function () {
if (this.files && this.files[0]) {
abc += 1; // Incrementing global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + abc).append($("<img/>", {
id: 'img',
src: 'images/x.png',
alt: 'delete'
}).click(function () {
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
}
;
$('#upload').click(function (e) {
var name = $(":file").val();
if (!name) {
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
<div id="maindiv">
<div id="formdiv">
<h2>Upload en delete pagina</h2>
<?php
if (isset($_SESSION['error'])) {
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload2.php" method="post" enctype="multipart/form-data">
<label>Merk</label>
<input type="text" name="fname" style="width:250px;"/><br />
<label>beschrijving</label>
<textarea name="lname" style="width:250px;height:150px;"></textarea><br />
<label>Upload afbeelding</label>
<div id="filediv"><input type="file" name="image" id="file"/></div>
<input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
<br /><br /><p>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<br /><br />
<input type="submit" value="Upload" name="submit" id="submit" class="upload" style="left:200px;"/>
</p>
</form>
<br /><br />
<p>
<form action="delete_multiple.php" method="post">
Wil je auto's van de site halen?
<input type="checkbox" name="formverkocht" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
</p>
</div>
</div>
thanks in advance guys!
You have spaces in ALL of your post parameters:
$fname = $_POST['fname '];
^--
That space DOES count for naming purposes, and is NOT the same as 'fname'. The keys in _POST/_GET must match EXACTLY what you have in the html:
<input type="text" name="foo"> -> $_POST['foo'] // note the LACK of a space
<input type="text" name="bar "> -> $_POST['bar '] // note the space

Categories

Resources