File not Uploading in File Reader - javascript

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

Related

How to delete uploaded files PHP ajax

I want to delete a file uploaded after I click on a submit button or after the page is reloaded.
I did this drop zone to drag and drop file:
<div id="drop_file_zone" class="centered" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file" class="centered">
<p><strong>Drop file here</strong></p>
<p>or</p>
<p>
<input class="btn btn-danger btn-sm" id="selectfile3" type="button" value="Select File" onclick="file_explorer();" />
</p>
<input type="file" id="selectfile"/>
<div class="img-content" style="text-align: center;"></div>
</div>
</div>
On my drag_drop.js file:
var fileobj;
function upload_file(e) {
e.preventDefault();
fileobj = e.dataTransfer.files[0];
ajax_file_upload(fileobj);
}
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function () {
fileobj = document.getElementById('selectfile').files[0];
ajax_file_upload(fileobj);
};
}
function ajax_file_upload(file_obj) {
if (file_obj != undefined) {
var form_data = new FormData();
form_data.append('file', file_obj);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/app/helpers/upload_file.php", true);
xhttp.onload = function (event) {
oOutput = document.querySelector('.img-content');
if (xhttp.status == 200) {
if(this.responseText == 'false'){
console.log('no type');
} else {
oOutput.innerHTML = "<img src='/app/assets/img/pdf.png' alt='The Image' width='32' height='32'/><p>" + this.responseText + "</p>";
}
} else {
oOutput.innerHTML = "Error " + xhttp.status + " occurred when trying to upload your file.";
}
}
xhttp.send(form_data);
}
}
And on the upload_file.php this function:
<?php
$arr_file_types = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
if (!(in_array($_FILES['file']['type'], $arr_file_types))) {
echo "false";
return;
}
if (!file_exists('uploads')) {
mkdir('uploads', 0777);
}
$filename = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $filename);
echo $filename;
die;
but I don't really know how to delete these temps documents when I press the button (this button will save the document on a database) or when the page is reloaded.

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

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 ##

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.

Reuse java script function to Show Multiple Images Preview

Hello!
I wrote the single java script function to show the image preview before uploading.
For single file uploading, my code is working fine.
But now i want to give multiple image uploading options by giving multiple select options to user(see the snapshot). Also for this, i want to reuse my function that is displaying the preview of selected first image.(see the image in snapshot)
How would i modify my html code and how to reuse my script function?
html
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="wrapper" style="margin-top: 20px;">
<input id="fileUpload" name="uploadedFile" type="file"/>
<input id="fileUpload2" name="" type="file"/>
<input id="fileUpload3" name="uploadedFile" type="file"/>
<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>
This is what classes are for. You are only calling your jQuery on the fileUpload Id. And if your going to use the same image holder for more than one image like this you should not be clearing it out each time.
I refactored your code a small amount. Try this.
html
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="wrapper" style="margin-top: 20px;">
<input class="fileUploadClass" id="fileUpload" name="uploadedFile" type="file"/>
<input class="fileUploadClass" id="fileUpload2" name="" type="file"/>
<input class="fileUploadClass" id="fileUpload3" name="uploadedFile" type="file"/>
<div id="image-holder"></div>
</div>
JavaScript
<script>
$(document).ready(function() {
$(".fileUploadClass").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");
}
});
});

Remove files after recieving previews but before uploading to server using FileReader (HTML5)

I have a JavaScript function that shows me the previews of the images I want to upload to the server. After recieving that previews I can select some of them by clicking and remove previews, but I need also to remove the selected files so they will not be uploaded to the server.
The following code can remove the previews but not the files. How can it be improved?
JavaScript:
$(document).ready(function () {
$("#image-holder").on('click', '.thumb-image', function () {
$(this).toggleClass("selectedItem");
});
$("#btnDelete").on("click", function () {
$(".selectedItem").remove();
});
$("#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 uploading.
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("Please select only images");
}
});
});
HTML:
<form method="POST" action="upload" enctype="multipart/form-data">
<input id="fileUpload" name="file" multiple="multiple" type="file"/>
<br/>
<input type="submit" value="Upload">
</form>
<button id="btnDelete">Delete</button>
I've done this before using AngularJS. In that case I just had to set the ng-model variable to undefined. I haven't tested this, but you should be able to accomplish the same thing by clearing your <input> value in a similar way.
$("#btnDelete").on("click", function () {
$(".selectedItem").remove();
$("#fileUpload").get(0).files[0] = undefined;
$("#fileUpload").removeAttr('value');
});

Categories