Multiple file upload and zip them on the fly failed - javascript

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.");
}

Related

How to Display Existing Files on Server in Dropzone JS?

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});
}

IMAGE COMPRESSOR Script [ Notice: Only variables should be passed by reference in ] [duplicate]

This question already has answers here:
Only variables should be passed by reference
(12 answers)
Closed 1 year ago.
I tried to take it off this error I do not understand why it happens, because I am uploading the file correctly... Right now is uploading the files, it shows me the error Error Notice: Only variables should be passed by reference in...
Notice: Only variables should be passed by reference in
D:\xampp\htdocs\reduce-image\upload.php on line 10
**
I am facing in upload.php code. It's showing this error:
**
```
**upload.php**
<pre>
<?php
$file_type_error = '';
if($_FILES['upload_images']['name']) {
$upload_dir = "uploads/";
if (($_FILES["upload_images"]["type"] == "image/gif") ||
($_FILES["upload_images"]["type"] == "image/jpeg") ||
($_FILES["upload_images"]["type"] == "image/png") ||
($_FILES["upload_images"]["type"] == "image/pjpeg")) {
$file_name = $_FILES["upload_images"]["name"];
$extension = end((explode(".", $file_name)));
$upload_file = $upload_dir.$file_name;
if(move_uploaded_file($_FILES['upload_images']['tmp_name'],$upload_file)){
$source_image = $upload_file;
$image_destination = $upload_dir."min-".$file_name;
$compress_images = compressImage($source_image, $image_destination);
}
} else {
$file_type_error = "Upload only jpg or gif or png file type";
}
}
// created compressed JPEG file from source file
function compressImage($source_image, $compress_image) {
$image_info = getimagesize($source_image);
if ($image_info['mime'] == 'image/jpeg') {
$source_image = imagecreatefromjpeg($source_image);
imagejpeg($source_image, $compress_image, 75);
} elseif ($image_info['mime'] == 'image/gif') {
$source_image = imagecreatefromgif($source_image);
imagegif($source_image, $compress_image, 75);
} elseif ($image_info['mime'] == 'image/png') {
$source_image = imagecreatefrompng($source_image);
imagepng($source_image, $compress_image, 6);
}
return $compress_image;
}
?>
</pre> ```
<pre>
<?php
include('header.php');
?>
<script type="text/javascript" src="scripts/jquery.form.js"></script>
<script type="text/javascript" src="scripts/upload.js"></script>
<link type="text/css" rel="stylesheet" href="style.css" />
<link type="text/css" rel="stylesheet" href="style.css" />
<div class="container">
<h2>Reduce or Compress Image Size While Uploading in PHP</h2>
<form method="post" name="upload_form" id="upload_form" enctype="multipart/form-data" action="upload.php">
<label>Choose Images to Upload</label>
<input type="file" name="upload_images" id="image_file">
<div class="file_uploading hidden">
<label> </label>
<img src="uploading.gif" alt="Uploading......"/>
</div>
</form>
<div id="uploaded_images_preview">
</div>
</div>
<?php include('footer.php');?>
</pre>`
**js.file**
<pre>
$(document).ready(function(){
$('#image_file').on('change',function(){
$('#upload_form').ajaxForm({
target:'#uploaded_images_preview',
beforeSubmit:function(e){
$('.file_uploading').show();
},
success:function(e){
$('.file_uploading').hide();
},
error:function(e){
}
}).submit();
});
});
</pre> ```
From the documentation of end
This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.
However you are passing it a function that returns an array.
Try
$parts = explode(".", $file_name);
$extension = end($parts);

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

Return new file name from mini-upload-form

I'm using Mini AJAX Upload Form to upload files to a server. I modified the upload code to add a time stamp the the end of the file. How can I return the new name of the file (with the time stamp) to the client for later use?
date_default_timezone_set('America/New_York');
$date = date('.YmdHis');
// A list of permitted file extensions
$allowed = array('sqlite', 'db', 'db3');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
$file = '/var/www/html/uploads/'.$_FILES['upl']['name'].$date;
if(move_uploaded_file($_FILES['upl']['tmp_name'], $file)){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
JS:
$(function(){
$('#drop a').click(function(){
// Simulate a click on the file input button
// to show the file browser dialog
$(this).parent().find('input').click();
});
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
url: 'includes/php/upload.php',
// This element will accept file drag/drop uploading
dropZone: $('#drop'),
});
// Prevent the default action when a file is dropped on the window
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
});
HTML snippet:
<div class="row">
<div class="col-lg-12 text-center">
<form id="upload" method="post" enctype="multipart/form-data">
<div id="drop">
<p>Drop Database Here</p>
<a>Browse</a>
<input type="file" name="upl" multiple/>
</div>
</form>
</div>
</div>
NOTE: Mini AJAX Upload Form uses jQuery-File-Upload
you can use the done call back to get he file name after upload it, of course you need to write it back to your ajax in you php script
done: function (e, data) {
$("tr:has(td)").remove();
$.each(data.result, function (index, file) {
$("#uploaded-files").append(
$('<tr/>')
.append($('<td/>').text(file.fileName))
.append($('<td/>').text(file.fileSize))
.append($('<td/>').text(file.fileType))
.append($('<td/>').html("<a href='upload?f="+index+"'>Click</a>"))
.append($('<td/>').text("#"+file.twitter))
)//end $("#uploaded-files").append()
});
},
also this example is java example but they do similar thing to what you do
http://hmkcode.com/java-servlet-jquery-file-upload/

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