How to Display Existing Files on Server in Dropzone JS? - javascript

In this blog, I will teach you how to display existing files or image on server in dropzone js. I will learn to show you existing image on dropzone js in php.
You can simply and easily to upload files or image on server using dropzone js. if you used dropzone js for uploading files and image then you might be need to show existing files or image from database using php mysql.
You will create just two files and one "upload" folder to make it done this example ,so just follow bellow example.
Create Index.php File
<!DOCTYPE html>
<html>
<head>
<title>How to Display Existing Files on Server in Dropzone JS - NiceSnippets.com</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.css' type='text/css' rel='stylesheet'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js' type='text/javascript'></script>
<style type="text/css">
.dz-preview .dz-image img{
width: 100% !important;
height: 100% !important;
object-fit: cover;
}
</style>
</head>
<body>
<div class="container" >
<h1>How to Display Existing Files on Server in Dropzone JS - NiceSnippets.com</h1>
<div class='content'>
<form action="upload.php" class="dropzone" >
</form>
</div>
</div>
<script type="text/javascript">
Dropzone.autoDiscover = false;
$(".dropzone").dropzone({
init: function() {
myDropzone = this;
$.ajax({
url: 'upload.php',
type: 'post',
data: {request: 'fetch'},
dataType: 'json',
success: function(response){
$.each(response, function(key,value) {
var mockFile = { name: value.name, size: value.size};
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, value.path);
myDropzone.emit("complete", mockFile);
});
}
});
}
});
</script>
</body>
</html>
Create upload.php File
<?php
/* Upload directory*/
$targetDir = "upload/";
$request = "upload";
if(isset($_POST['request'])){
$request = $_POST['request'];
}
/* Upload file */
if($request == "upload"){
$msg = "";
if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetDir.$_FILES['file']['name'])) {
$msg = "Successfully uploaded";
}else{
$msg = "Error while uploading";
}
echo $msg;
exit;
}
/* Read files from */
if($request == 'fetch'){
$fileList = [];
$dir = $targetDir;
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '' && $file != '.' && $file != '..'){
$file_path = $targetDir.$file;
if(!is_dir($file_path)){
$size = filesize($file_path);
$fileList[] = ['name'=>$file, 'size'=>$size, 'path'=>$file_path];
}
}
}
closedir($dh);
}
}
echo json_encode($fileList);
exit;
}

It's because the internal function of react-native-weekday-picker mutates the same object (repeatDays in your case) passed to the library.
see here
and thought, you are setting a new state before rendering component the React compares prev value and current value but since it's of the same reference it doesn't rerender
const RepeatDaysHandle = (repeatDays) => {
console.log(repeatDays);
setWeekDays({...repeatDays});
}

Related

How to drag and drop .enc file into web browser from desktop and send it to php file for processing?

I want to implement a drag and drop functionality for my webpage by which I can upload .enc file from desktop to webpage and send it to my PHP file for processing.
I have tried a solution which I found on the internet which does not seem to be working.
Here is the code:
<div id="drop_file_zone" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file">
<p style="color:#00B3E6"><b>Drop file here</b></p>
<input type="file" name="dragfile" id="dragfile">
</div>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
var fileobj;
function upload_file(e) {
e.preventDefault();
fileobj = e.dataTransfer.files[0];
ajax_file_upload(fileobj);
}
function ajax_file_upload(file_obj) {
if(file_obj != undefined) {
var form_data = new FormData();
form_data.append('dragfile', file_obj);
$.ajax({
type: 'POST',
url: 'upload.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
alert(response);
$('#dragfile').val('');
}
});
}
}
</script>
Do you have upload.php ? That is the file which actually uploads the dragged file. It could be like this.
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['dragfile']['name']);
$actual_name = basename( $_FILES['dragfile']['name']);
if(#move_uploaded_file($_FILES['dragfile']['tmp_name'], $target_path)) {
$result = 1;
echo $target_path;
}
else {
echo "Error! Could not upload file.";
}
sleep(1);
?>

Dynamically inject PHP as form action redirects to 404 page

So what I'm doing is dynamically creating a form and input elements in a document with JS like so:
document.ondblclick = function(e) {
if (e.clientX < 50 && e.clientY > window.innerHeight - 50
&& !document.querySelector('form')) {
const b = document.body
const f = document.createElement('form')
const i = document.createElement('input')
b.style.width = '100vw'
b.style.height = '100vh'
b.style.margin = '0'
b.style.display = 'flex'
b.style.justifyContent = 'center'
b.style.alignItems = 'center'
i.setAttribute('type', 'password')
i.setAttribute('name', 'password')
i.setAttribute('id', 'form')
f.setAttribute('method', 'post')
f.setAttribute('action', '<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>')
f.appendChild(i)
b.appendChild(f)
i.focus()
i.onblur = function() {
i.focus()
}
}
}
However, it's as if the browser ignores the PHP and, instead of returning to the current file, consequently gets redirected to the 404 page.
Below is the HTML, PHP, and the file structure of the directory.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] === "POST" && !empty($_POST["password"])) {
include "php/connect.php";
$stri = "SELECT password FROM account";
$stat = $conn->prepare($stri);
$stat->execute();
$resu = $stat->fetch(PDO::FETCH_ASSOC);
if (password_verify($_POST["password"], $resu["password"])) {
$_SESSION["session"] = $resu["password"];
$conn = null;
echo 'SUCCESS';
}
$conn = null;
}
?>
<!DOCTYPE html>
<head>
<title>‎</title>
<meta charset="UTF-8">
</head>
<body>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
The directory is structured like so...
public_html >
trading-toolbox >
css > index.css
js > index.js
php > connect.php
index.php
Why is it redirecting to the 404 page? What am I doing wrong here? Is the action attribute of the form treated as a string since it is set dynamically with JS?
The problem is your index.js file. Notice the file ending? .js is a javascript file, and will be treated by your server as a static file, only serving the contents and not processing the file. The easiest solution is to rename it to index.php and then include it like normal:
<script type="text/javascript" src="js/index.php"></script>
You need name your .js file as .php and send headers for expose the file as javascript and use $_SESSION to send the action file from index to JS
<?php
header('content-type:application/javascript; charset=utf-8');
?>
...
f.setAttribute('action', '<?php echo htmlspecialchars($_SESSION["formFile"]); ?>')
...
Then in your index file add and change
<?php $_SESSION["formFile"] = $_SERVER["PHP_SELF"]; ?>
<script type="text/javascript" src="js/index.php"></script>

Multiple file upload and zip them on the fly failed

I have created multiple file uploader using html & php. Uploader functionality works fine but while I try to create a ZIP on the fly in order to add uploaded file into ZIP file. In that case, failed to create zip and add uploaded file into zip. I don't know why it's not working.
Please check my scripts below and let me know if I missed anything thanks in advance:
Html scripts:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File Upload with Progress Bar</title>
<script type="text/javascript">
// select file function only for styling up input[type="file"]
function select_file(){
document.getElementById('image').click();
return false;
}
</script>
</head>
<body>
<div class="container">
<!--status message will appear here-->
<div class="status"></div>
<!--image upload form-->
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a file</a>
<input id="image" type="file" multiple="multiple" name="files[]" >
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
</div>
</body>
</html>
Php Scripts:
header('Content-type: application/json');
$path = 'uploads/'; // upload directory
if (!file_exists('uploads')) {
mkdir('uploads', 0777, true);
}
$max_file_size = 1024*10000; // 1024 byte= 1kb 1024*100 byte=100kb
$count = 0;
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
$zip_path = 'download.zip';
$zip = new ZipArchive();
if ($zip->open($zip_path, ZIPARCHIVE::OVERWRITE) !== TRUE) {
die ("An error occurred creating your ZIP file.");
}
foreach ($_FILES['files']['name'] as $f => $name) {
$filename = $_FILES['files']['name'][$f];
$filecontent = file_get_contents($_FILES["files"]["tmp_name"][$f]);
$filetype = $_FILES['files']['type'][$f];
$filesize = $_FILES['files']['size'][$f];
$fileext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);;
$zip->addFromString($filename, $filecontent);
//$zip->addFile('file_on_server.ext', 'second_file_name_within_archive.ext');
if ($_FILES['files']['error'][$f] == 4) {
$status[] ='Upload Fail: Unknown error occurred!';
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$status[] = "$name is too large!.";
continue; // Skip large files
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name)){
$count++; // Number of successfully uploaded file
$status[] = 'Image successfully uploaded!';
}
else {
$status[] = 'Upload Fail: Unknown error occurred!';
}
}
}
}
$zip->close();
}
else {
$status[] = 'Bad request!';
}
echo json_encode(array('status' => $status));
It's not working probably download.zip file doesn't exist in your directory.
Could you please create download.zip file or replace your following code then try again:
if ($zip->open($zip_path,ZIPARCHIVE::OVERWRITE) !== TRUE)
{
die ("An error occurred creating your ZIP file.");
}
With
if ($zip->open($zip_path,ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE)
{
die ("An error occurred creating your ZIP file.");
}

jQuery Ajax form two submit button in one form

I have 2 button in one form. When I click the first or second button, both write example an alert, but the Ajax request doesn't run. I need a form, because i would like to upload images. I don't know what is the problem.
page.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Ajax two submit in one form</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<form id="animal-upload" method="post" enctype="multipart/form-data">
<span>Name:</span>
<input type="text" name="animalname" id="animalname">
<span>Image:</span>
<input type="file" name="imagefile" id="imagefile">
<button type="submit" name="publish" id="publish">Publish</button>
<button type="submit" name="save" id="save">Save</button>
</form>
<script>
$(document).ready(function() {
$('#animal-upload').on('submit', function() {
return false;
});
$('#publish').click(function() {
alert("Test");
});
$('#save').click(function(e) {
e.preventDefault();
$.ajax({
url: "animal-upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
alert(data);
}
});
});
});
</script>
</body>
</html>
animal-upload.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test");
mysqli_set_charset($connect,"utf8");
$status = '';
$animalname = $connect->real_escape_string($_POST["animalname"]);
if ($_FILES['imagefile']['name'] != '') {
$extension = end(explode(".", $_FILES['imagefile']['name']));
$allowed_type = array("jpg", "jpeg", "png");
if (in_array($extension, $allowed_type)) {
$new_name = rand() . "." . $extension;
$path = "animals/" . $new_name;
if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $path)) {
mysqli_query($connect, "INSERT INTO animals (animalname,image) VALUES ('".$animalname."','".$path."')");
$status = 'Successful!';
}
} else {
$status = 'This is not image file!';
}
} else {
$status = 'Please select image!';
}
echo $status;
?>
After trial and errors I found the script work if you change this line :
data: new FormData($("#animal-upload")[0]),
Because that selects the form object.
You may consider some security tips :
Don't divulge your password in public
Don't let your database users connect without passwords
Make a user with strict minimum privileges just for the purpose to connect to your database from PHP scripts (it's called the principle of least privileges)
Rename your uploaded file
For the file upload to work :
Make sure you have the right permissions on the directory pointed by
upload_tmp_dir in php.ini file
You may need to check that your file size doesn't exceed the memmory_limit directive too
good luck,

search folder on server and display results

How do I search a folder on my server and display the results on my webpage? I found a similar question at How can I create a search form that searches files in a folder? but I can't figure out how to connect the php script to my html:
<!DOCTYPE html>
<html>
<body>
<div>
<input id="query" type="text"/><button id="search-button" onclick="?????">Search</button>
</div>
<script>
var q=document.getElementById("query");
</script>
<?php
$dir = "/uploads/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($file == $_POST['q']){
echo(''. $file .''."\n");
}
}
closedir($dh);
}
}
?>
</body>
</html>
You can post info to a php script seamlessly (asynchronously) with jQuery's post method. Then you can return the data to the calling page and display it.
So have the php script that lists/finds the files and the html page separate. Then in the html page use javascript and jQuery to post to that php finder script. Something like:
$.post('phpFileFinder.php', {fileName: fileNameJSvar}, function(data){
$("#divId").html(data);
});
Then in your php script you can have:
$dir = $_POST['fileName'];
$fileArray = array();
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($file == $_POST['q']){
array_push($fileArray,''. $file .''."\n");
}
}
closedir($dh);
}
print_r($fileArray);
}

Categories

Resources