How to upload image with php, js and local storage? - javascript

I have managed to upload an image with PHP and HTML before but now I have to do this with js and ajax. And I have been advised to also use local storage to store it on the server before insert it into the database. I have started and had a little go. I have added the php, html and js code below. Thanks in advance for any help.
$username = $_POST['username'];
$message = "Hello!";
if($_POST['submit'] == "Upload Image"){
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$message = "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$message = "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
$message = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$message = "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$message = "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)) {
$uploadedfilename= basename( $_FILES["fileToUpload"]["name"]);
$query = "UPDATE users SET imagename='$uploadedfilename' WHERE username='$username'";
mysqli_query($db_server, $query) or die("Insert failed. ". mysqli_error($db_server));
$message = "<strong>Image $uploadedimage upload successful!</strong>";
} else {
$message = "Sorry, there was an error uploading your file.";
}
}
}
$currentimagename = "profilepic.png";
$query="SELECT imagename FROM users WHERE username='$username'";
$result = mysqli_query($db_server, $query) or die("image load failed. ". mysqli_error($db_server));
if($row = mysqli_fetch_array($result)){
if($row['imagename']<>""){
$currentimagename = $row['imagename'];
}
}
mysqli_free_result($result);
echo $message;
HTML
<h2 id="username" class="usernamemessage"></h2>
<img src="profilepic.png" alt="profilepic" style="width:200px;height:200px;">
<div class="buttons">
<button class="button">Upload Image</button>
<form id="imageForm" method='POST' class="imageform">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
JS
// When upload image button is clicked
$(document).ready(function() {
var imageform = $("#imageForm");
$("#imageForm").on('submit', function(event) {
event.preventDefault();
var imageValue = document.getElementById("fileToUpload").value;
var imageform = new FormData(this);
//Get Storage
var username = window.localStorage.getItem("username");
imageform.append('username', username);
// Call AJAX
$.ajax({
type: 'POST',
url: 'image.php',
data: imageform,
processData: false,
contentType: false,
success: function(response) {
if(response == "Success"){
document.getElementById("image").innerHTML = "Image Change Successful";
//Local Storage
window.localStorage.setItem("fileToUpload", imageValue);
} else {
console.log(response);
document.getElementById("error").innerHTML = response;
}
}
});
return false;
});
});

I have seen in your form tag you didn't added below part
enctype='multipart/form-data'
Please add this in form tag your code will work## Heading ##

Related

Uploading multipile files using HTML file input

i'm trying to upload a bunch of files using file type input with php i tried so far to make upload only one file and it worked the problem is that when i added [] to the name attribute it started to print Uploaded data error.
HTML
<form id="theform" action="upload.php" onsubmit="event.preventDefault(); return myFunction2();" method="post" enctype="multipart/form-data">
<input id="file" name="uploadedFile[]" onchange="uptoserver();" style="display:none;"type="file" multiple>
<div class="row justify-content-center">
<div id="buttons" style="display:none !important;">
<button type="submit" class="btn wbtn" style="font-family:Hana; font-size:18px; border:1px solid black !important;">
<img src="style\image\add.png" width="32" /> تكوين كشف
</button>
<button type="button" class="btn wbtn" style="font-family:Hana; font-size:18px; border:1px solid black !important;">
<img src="style\image\camera.png" width="32" /> إضافة نموذج
</button>
</div>
</div>
</form>
Javacript :
function myFunction2(){
document.getElementById('file').click();
console.log('reading form');
}
function uptoserver(){
// var formscounter = parseInt(document.getElementById("counter").value);
if(!document.getElementById("file").files.length == 0) {
const form = document.getElementById('theform');
form.submit();
console.log('fucking working');
}
}
upload.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo "Empty data, please select file";
die;
}
if (!isset($_FILES["uploadedFile"])) {
echo "Wrong data struct";
die;
}
if ($_FILES["uploadedFile"]['error'] != 0) {
echo "Uploaded data error";
die;
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["uploadedFile"]["name"]);
$allowUpload = true;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$maxfilesize = 80000000;
$allowtypes = array('jpg', 'png', 'jpeg', 'gif');
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["uploadedFile"]["tmp_name"]);
if($check !== false) {
//
} else {
echo "This's not image file.";
$allowUpload = false;
}
}
if (file_exists($target_file)) {
require "other\\fileExsist.php";
$allowUpload = false;
}
if ($_FILES["uploadedFile"]["size"] > $maxfilesize) {
require "other\\fileSize.php";
$allowUpload = false;
}
if (!in_array($imageFileType,$allowtypes )) {
require "other\\fileExtenstion.php";
$allowUpload = false;
}
if ($allowUpload) {
if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) {
// echo "File ". basename( $_FILES["uploadedFile"]["name"]). " uploaded success.";
// echo $target_file;
require "prepare.php";
echo count($_FILES["uploadedFile"]);
} else {
echo "Error when upload file.";
}
// $total = count($_FILES['uploadedFile']['name']);
// // Loop through each file
// for( $i=0 ; $i < $total ; $i++ ) {
// //Get the temp file path
// $tmpFilePath = $_FILES['uploadedFile']['tmp_name'][$i];
// //Make sure we have a file path
// if ($tmpFilePath != ""){
// //Setup our new file path
// $newFilePath = "uploads/" . $_FILES['uploadedFile']['name'][$i];
// //Upload the file into the temp dir
// if(move_uploaded_file($tmpFilePath, $newFilePath)) {
// //Handle other code here
// }
// }
// }
} else {
echo "";
}
?>
Your original structure works perfectly fine because, when you're uploading a single file, line 18 is if ($_FILES["uploadedFile"]['error'] != 0), and this returns 0.
When you send through an array of files, even if a single file is sent, the uploadFile array is now an array of arrays, as below.
[_FILES] => Array
(
[uploadedFile] => Array
(
[name] => Array
(
[0] => funnyMusclePose.jpg
)
[type] => Array
(
[0] => image/jpeg
)
[tmp_name] => Array
(
[0] => C:\Development\wamp64\tmp\phpE949.tmp
)
[error] => Array
(
[0] => 0
)
[size] => Array
(
[0] => 735092
)
)
)
This means $_FILES["uploadedFile"]['error'] will always evaluate to true because it doesn't equal 0.
From here on out, you can wrap this entire function in a for() loop and iterate over each of the internal array items to get the data you're after, ie.
for($i = 0; $i < count($_FILES["uploadedFile"]["name"]); $i++) {
if ($_FILES["uploadedFile"]['error'][$i] != 0)
{
echo "Uploaded data error";
die;
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["uploadedFile"]["name"][$i]);
$allowUpload = true;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$maxfilesize = 80000000;
$allowtypes = array('jpg', 'png', 'jpeg', 'gif');
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["uploadedFile"]["tmp_name"][$i]);
if($check !== false)
{
//
}
else
{
echo "This's not image file.";
$allowUpload = false;
}
}
if (file_exists($target_file))
{
require "other\\fileExsist.php";
$allowUpload = false;
}
if ($_FILES["uploadedFile"]["size"][$i] > $maxfilesize)
{
require "other\\fileSize.php";
$allowUpload = false;
}
if (!in_array($imageFileType,$allowtypes ))
{
require "other\\fileExtenstion.php";
$allowUpload = false;
}
// Add the rest of the code here
}

Uploading an image, then displaying it as a Canvas on the next page

I'm attempting to create a page that allows the manipulation of an uploaded image by using Canvas. So far, I've had no luck forwarding the image from one page (the submit form) to the other, which contains the canvas. I'm using PHP, Javascript and HTML in order to try and send the image from the submit form to the canvas space.
This is the submitting form.
<form action="designer.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label><?php
include('/tbp3/php/autoload.php');
header('Content-Type: application/json');
$fullpath = $_SESSION['activeImg'];
$size = getimagesize($fullpath);
echo json_encode(array('x' => $size[0], 'y' => $size[1], 'path' => $fullpath, 'lastPosJson' => isset($_SESSION['lastPos']) ? $_SESSION['lastPos'] : '[]'));
$db->close();
?>
<p>2-32 characters</p>
<input class="form-control" type="text" name="name" id="name">
</div>
<div class="form-group">
<p>JPEG/PNG under 2MB only</p>
<label class="btn btn-default" for="image">Choose Image</label>
<span></span>
<input class="inputfile" type="file" name="image" id="canvas">
</div>
<div class="form-group">
</div>
<input class="btn btn-primary" type="submit" value="Next">
</form>
This is the JavaScript I use in order to confirm the uploaded file is a PNG or JPEG. Note: I'm a novice at Javascript.
var validTypes = ['png', 'jpg', 'jpeg'];
$(document).ready(function(){
$('form').submit(function(e){//on submission..
var file = $('#upload').val();
var isValid = true;
var error = '';
if(file == ''){
error = 'Select a file before proceeding!';
$('#upload').addClass('validation-error');
isValid = false;
} else{
var type = /[^\.]*$/.exec(file).toString().toLowerCase();
if($.inArray(type, validTypes) == -1){
error = type + ' is an invalid type for the image! Please use ' + validTypes.join(', ').replace(/,([^,]*)$/, " or$1.");
$('#upload').addClass('validation-error');
isValid = false;
}
}
});
And this is on the page 'Designer.php'. I want the image to be displayed on the tag.
<div class="row canvasarea">
<div class="col-xs-6 header">Canvas</div>
<div class="col-xs-6 header">Live View</div>
</div>
<div class="row canvasarea">
<div class="col-xs-6 help">TEXT</div>
<div class="col-xs-6 help">TEXT</div>
</div>
<div class="row canvasarea">
<div class="col-xs-6">
<canvas id='canvas'></canvas></div>
<div class="col-xs-6">
<img id='liveupdate'/><br></div>
The PHP script I'm using to save it to the server.
<?php
require('/var/www/html/tpb3/php/autoload.php');
session_start();
$megabyte = 8000000;
$db = "new Database();";
function getImage(){
$id = $this->getTemplateId();
$type = $this->getFiletype();
return "img/template/$id.$type";
}
function addTemplate($templateId, $filetype){
if(!$this->isLoggedIn()){
echo "You're not logged in";
return '';
}
function isValidFileType($type){
$type = strtolower($type);
$types = array('jpeg', 'jpg', 'png');
for($i = 0; $i < count($types); $i++){
if($type === $types[$i]){
return true;
}
}
return false;
}
function isPng($filepath){
$img = #imagecreatefrompng($filepath);
if($img === false){
return false;
} else{
echo "Not a PNG";
imagedestroy($img);
return true;
}
}
function isJpeg($filepath){
$img = #imagecreatefromjpeg($filepath);
if($img === false){
return false;
} else{
echo "Not a JPEG";
imagedestroy($img);
return true;
}
}
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
if(!empty($_POST['selectedType']) ){
$selectedType = $_POST['type'];
}
if(isset($_POST["type"]))
$selectedType = $_POST["type"];
$dir = $selectedType == 'template' ? 'temp' : 'sourceimages';
if(isset($_POST["submit"])) {
$valid = true;
$id = uniqid();
$type = strtolower(pathinfo(basename($_FILES['upload']['name']), PATHINFO_EXTENSION));
$uploadFileDest = 'img/template/$id.$type';
$size = #getimagesize($_FILES["upload"]["tmp_name"]);
$error = '';
if($size === false) {
$error .= "Main image not a valid image, ";
$valid = false;
} elseif($size[0] > 2000 || $size[1] > 2000){
$error .= "Image larger than 2000px, ";
$valid = false;
} elseif(!isValidFileType($type)){
$error .= "Not a valid filetype, ";
$valid = false;
} elseif(!isJpeg($_FILES["upload"]["tmp_name"]) && !isPng($_FILES["upload"]["tmp_name"])){
$error .= "Image is not a valid jpg/png. ";
$valid = false;
} elseif ($_FILES["upload"]["size"] > 2 * $megabyte) {
$error .= "File larger than 2 MB, ";
$valid = false;
}
}
if($valid = true){
if($selectedType == 'template'){
$_SESSION['activeId'] = $id;
$_SESSION['activeImg'] = $uploadFileDest;
move_uploaded_file($_FILES["upload"]["tmp_name"], $uploadFileDest);
header('Location: designer.php');
} else{
$response = $db->addSourceImage($id, $type);
if($response == ';success'){
move_uploaded_file($_FILES["upload"]["tmp_name"], $uploadFileDest);
$_SESSION['lastId'] = $id;
header('Location: success.php');
} else{
header('Location: submit.php?e='.urlencode("Database failed with message: $response"));
}
}
} else{
header('Location: submit.php?e='.urlencode(substr($error, 0, strlen($error) - 2)));
}
}
?>
Any push into the right direction would be appreciated.

Uploaded file is not passing through JavaScript to PHP

Here i'm trying to pass uploaded file and a text input from HTML->JavaScript->PHP. But it is only passing the text input and failed to pass the file , i'm not getting that file in PHP. As a result it is showing undefined index error for "$u_file" in the PHP file. I don't understand where is the problem.
Here goes the HTML file
<body>
<div class="container">
<form class="form-horizontal" action="">
<h2><b>Post your job</b></h2><br><br>
<div class="form-group">
<label class="control-label col-sm-2">Job Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="jName" placeholder="Enter job name" name="jName" required>
<p id="jErr"></p>
</div>
</div>
<div class="form-group">
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
<label class="control-label col-sm-2">Add some detailed description:</label>
<div class="col-sm-10">
<input id="u_file" value="u_file" type="file" name="u_file" size="5000000" multiple onchange="showname()"><br><br>
</div>
</form>
</div>
<div class="container-fluid text-center">
<br><button name="submitJob" id="submitJob" type="submit" class="btn btn-default" onclick="job_checker()">Submit</button>
<p id="submitJobErr"></p></div>
</form>
</div>
</body>
Here goes the JavaScript file
signFlagj = 0;
function job_checker() {
checkJobName();
databasejobEntry();
}
function checkJobName() {
var jobnameET = document.getElementById("jName");
var jobnameError = document.getElementById("jErr");
jobname = jobnameET.value;
console.log(jobname);
var regex = /^[a-zA-Z ]*$/;
if(!regex.test(jobname)){
jobnameError.innerHTML = "Only letters and white space allowed";
signFlagj = 1;
}
else {
jobnameError.innerHTML = "";
}
}
function showname() {
jobFilename = document.getElementById('u_file');
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log('Selected file: ' + jobFilename.files.item(0).size);
console.log('Selected file: ' + jobFilename.files.item(0).type);
}
function databasejobEntry() {
if(signFlagj==1) {
console.log("fill up correctly!");
alert("Sign up correctly!");
}
else
{
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log(jobname);
var submitError = document.getElementById("submitJobErr");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
console.log(response);
submitError.innerHTML=response;
alert(response);
if(String(response.trim()) === "Success") {
alert("Successfully submitted :)");
window.location.href = "uploadJob.html";
}
}
}
xhttp.open("GET", "uploadJob.php?jobname="+jobname+"&jobFilename="+jobFilename,true);
xhttp.send();
}
}
Here goes the PHP file
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$val="";
$jobName = $_GET["jobname"];
echo "$jobName";
$u_file = $_FILES['jobFilename'];
$file_type = $_FILES['jobFilename']['type'];
$file_size = $_FILES['jobFilename']['size'];
$file_name = $_FILES['jobFilename']['name'];
print_r($u_file);
//echo "****************";
$currentdir = getcwd();
$targetfolder = $currentdir . "/testupload/";
// echo "****************";
print_r($targetfolder);
$targetfile = $targetfolder . basename( $_FILES['jobFilename']['name']) ;
//print_r($targetfolder);
print_r($currentdir);
//echo "****************";
$uploadOk=1;
print_r($file_type);
if ($file_type != "application/pdf" && $file_type != "image/png" && $file_type != "image/jpeg" && $file_type != "image/jpg") {
echo "Sorry, only JPG, JPEG, PNG & PDF files are allowed.";
$uploadOk = 0;
}
if (file_exists($targetfile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if($uploadOk==0){
echo "Problem in uploading file";
}
else {
if(move_uploaded_file($_FILES['jobFilename']['tmp_name'], $targetfile)) {
$fileUpQueryjob = "INSERT INTO jobs (job_name,job_filename) VALUES ('$jobName','$file_name')";
$upJob = $db->query($fileUpQueryjob);
if ($upJob == true) {
$val = "Success";
echo "The file ". basename( $_FILES['jobFilename']['name']). " is uploaded";
}
else
echo "Error: " . $fileUpQueryjob . "<br>" . mysqli_error($db);
}
}
//echo "$val";
$db->close();
Use POST request instead of GET request. If necessary warp it in new FormData and post it.

File not Uploading in File Reader

I am using File Reader for selecting and uploading images.
My images are selected previewing but not uploaded when i hit submit button.
In upload.php the output of $_FILES is an empty array.
Where is problem?
html
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="wrapper" style="margin-top: 20px;">
<input id="fileUpload" multiple="multiple" type="file"/>
<input type="submit" value="Upload Image" name="upload">
<div id="image-holder">
</div>
</div>
</form>
Javascript
<script>
$(document).ready(function() {
$("#fileUpload").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++)
{
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
});
</script>
upload.php
<?php
require_once './include/db_connection.php';
if(isset($_POST['upload']))
{
print_r($_FILES);
die();
if(!empty($_FILES)){
$targetDir = "upload/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile))
{
//insert file information into db table
$sql = mysqli_query($link,"INSERT INTO files (file_name, uploaded) VALUES('".$fileName."','".date("Y-m-d H:i:s")."')");
echo 'file inserted';
}
else
{
echo 'Query not working';
}
}
else
{
echo 'No file selected';
}
}
Your file input doesn't have a name.
The name of a form control is used to determine what key it will have in the submitted data. Controls without them will not be successful (i.e. will not appear in the submitted data at all).

Alert error message gets displayed multiple times

The code is shown below:
if(isset($_FILES['hiddenfilebutton'])){
$img_name = $_FILES['hiddenfilebutton']['name'];
$img_temp = $_FILES['hiddenfilebutton']['tmp_name'];
$a = explode('.',$img_name);
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$img_extension = strtolower(end($a));
unset($a);
$img_size = $_FILES['hiddenfilebutton']['size'];
if($img_size > 3000000) {
$error = 'Image should be less than 4 MB';
} else if(!in_array($img_extension, $allowed_ext)) {
$error = "Unsupported image format";
}
}
?>
<script type="text/javascript">
if('<?php echo $error; ?>' != '' && '<?php echo $error; ?>' != undefined) {
alert("<?php echo $error; ?>");
}
</script>
Problem is that whenever I upload an unsupported image type like a .tiff image, the alert box gets displayed. This works the way I want it to work. But if i reload it, then it displays the alert box once again with the same message. It doesn't show up the third time I reload. I want alert message to show up only once, not twice or thrice..
change code to:
<?php
if(isset($_FILES['hiddenfilebutton'])){
$img_name = $_FILES['hiddenfilebutton']['name'];
$img_temp = $_FILES['hiddenfilebutton']['tmp_name'];
$a = explode('.',$img_name);
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$img_extension = strtolower(end($a));
unset($a);
$img_size = $_FILES['hiddenfilebutton']['size'];
if($img_size > 3000000) {
$error = 'Image should be less than 4 MB';
} else if(!in_array($img_extension, $allowed_ext)) {
$error = "Unsupported image format";
}
}
if(isset($error)){
?>
<script type="text/javascript">
alert("<?php echo $error; ?>");
</script>
<?php
}
?>
OR
<?php
if(isset($_FILES['hiddenfilebutton'])){
$img_name = $_FILES['hiddenfilebutton']['name'];
$img_temp = $_FILES['hiddenfilebutton']['tmp_name'];
$a = explode('.',$img_name);
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$img_extension = strtolower(end($a));
unset($a);
$img_size = $_FILES['hiddenfilebutton']['size'];
if($img_size > 3000000) {
$error = 'Image should be less than 4 MB';
} else if(!in_array($img_extension, $allowed_ext)) {
$error = "Unsupported image format";
}
}
if(isset($error)){
echo "<script type='text/javascript'> alert('<?php echo $error; ?>'); </script>";
}
?>

Categories