Having problem with uploading multiple files in one request using dropzone - php

Am trying to update user image database column using dropzone plugin in one request but when i set uploadMultiple to true is not working no image move to folder neither database. But when i set it to false only last image name move to user image column but all images move to folder.
Thanks in advance
Here is my code
Dropzone.options.mydropzone =
{
autoProcessQueue: false,
addRemoveLinks: true,
dictMaxFilesExceeded: "Maximum upload limit reached",
dictInvalidFileType: "upload only JPG/PNG/JPEG/GIF/BMP",
acceptedFiles: '.png,.jpg,.jpeg,.gif,.bmp',
parallelUploads: 10,
// uploadMultiple: true,
init: function ()
{
var submitButton = document.querySelector('#letupload');
myDropzone = this;
submitButton.addEventListener("click", function(){
myDropzone.processQueue();
});
this.on("complete", function(){
if (this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
{
var _this = this;
_this.removeAllFiles();
}
//console.log(this.getUploadingFiles());
});
},
};
Server Side
if (!empty($_FILES)) {
$temp_file = $_FILES['file']['tmp_name'];
$targetDir = '../../user_images/';
$filename = rand().$_FILES['file']['name'];
$targetFile = $targetDir.$filename;
if (move_uploaded_file($temp_file, $targetFile)) {
$sql="UPDATE img SET Image='$filename' WHERE User_id = '$memberid' ";//
if(!$qsql=mysqli_query($con,$sql))
{
echo mysqli_error($con);
}
}
}
After follow Mohammed link every images to to destination folder but only last image save into that database Below is my new server side code
if (!empty($_FILES)) {
foreach($_FILES['file']['tmp_name'] as $key => $value) {
$temp_file = $_FILES['file']['tmp_name'][$key];
$targetDir = '../../user_images/';
$filename = rand().$_FILES['file']['name'][$key];
$targetFile = $targetDir.$filename;
if (move_uploaded_file($temp_file,$targetFile)) {
$sql="UPDATE img SET Image='$filename' WHERE User_id = '$memberid' ";//
if(!$qsql=mysqli_query($con,$sql))
{
echo mysqli_error($con);
}
}
}
}

You are updating at each iteration , so the value at the end of script will be the name of the last image uploaded , so there is a way to solve this issue trying this snippet of code :
Insert into an array (i nammed id $images) the file name of uploaded
files.
convert array into spring separated by comma , using implode
function .(i used the same variable $images).
update the row with images name .
Code example :
if (!empty($_FILES)) {
$images=array[];
foreach($_FILES['file']['tmp_name'] as $key => $value) {
$temp_file = $_FILES['file']['tmp_name'][$key];
$targetDir = '../../user_images/';
$filename = rand().$_FILES['file']['name'][$key];
$targetFile = $targetDir.$filename;
if (move_uploaded_file($temp_file,$targetFile)) {
$images[]= $filename;
}
}
$images = implode(',',$images);
$sql="UPDATE img SET Image='$images' WHERE User_id = '$memberid' ";//
if(!$qsql=mysqli_query($con,$sql)){
echo mysqli_error($con);
}
}
Hope this help you .

Thanks to #Mohammed after I try your code, the problem of saving images name into database still persist, I now discover that you declare empty array inside the foreach so below is the working code
Dropzone Js
Dropzone.options.mydropzone =
{
autoProcessQueue: false,
addRemoveLinks: true,
dictMaxFilesExceeded: "Maximum upload limit reached",
dictInvalidFileType: "upload only JPG/PNG/JPEG/GIF/BMP",
acceptedFiles: '.png,.jpg,.jpeg,.gif,.bmp',
parallelUploads: 10,
uploadMultiple: true,
init: function ()
{
var submitButton = document.querySelector('#letupload');
myDropzone = this;
submitButton.addEventListener("click", function(){
myDropzone.processQueue();
});
this.on("complete", function(file, response){
if (this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
{
var _this = this;
_this.removeAllFiles();
}
console.log(this.getUploadingFiles());
});
},
};
Server Side
if (!empty($_FILES)) {
$empty_img_arr=array();
foreach($_FILES['file']['tmp_name'] as $key => $value) {
$temp_file = $_FILES['file']['tmp_name'][$key];
$targetDir = '../../user_images/';
$filename = rand().$_FILES['file']['name'][$key];
$targetFile = $targetDir.$filename;
if (move_uploaded_file($temp_file,$targetFile)) {
$empty_img_arr[]= $filename;
$image = implode(',',$empty_img_arr);
$sql="UPDATE img SET Image='$image' WHERE User_id = '$memberid' ";//
if(!$qsql=mysqli_query($con,$sql))
{
echo mysqli_error($con);
}
}
}
}
Thanks so much really appreciate

Related

Drag and Drop jQuery & Ajax upload file and sending html form data all together

I want to be able to have a user drag and drop a pdf file and have a modal appear for the user to quickly fill out a form about the file. When the user clicks submit, the file and the form data are passed using Ajax to a php file to then have the file upload and the data processed into a DB.
script.js
// On drop calls uploadFile Function and appends to formData object
$("#dropzone").on ('drop', function (e) {
e.preventDefault();
$(this).removeClass('dropzone dragover').addClass('dropzone');
$("#myModal").removeClass("hidden").addClass("visible");
var file = e.originalEvent.dataTransfer.files;
uploadFile(file);
});
var uploadFile = function(files){
formData = new FormData();
formData.append("file", files);
var x;
for (x = 0; x < files.length; x = x + 1){
let file = files[x];
formData.append('files[]', file);
}
};
// On Form submit all data is saved to values and Ajax call to users.php
$("form").on('submit', function(e) {
// e.preventDefault();
var values = $(this).serialize();
$("#myModal").removeClass("visible").addClass("hidden");
url = 'app/forms/users.php'
$.ajax({
type: 'POST',
url: 'app/forms/users.php',
processData: false,
contentType: false,
cache: false,
data: { formData, values },
dataType: 'json',
success: console.log("Done")
});
});
This is where I run into issues. I am able to
console.log(Array.from(formData)) at all points of interaction before the user hits submit. But when the user submits the form it seems the formData vanishes from existence.
users.php
} else if ($_POST['dispatch'] == 'file_upload') {
// Upload File
var_dump($_FILES);
var_dump($_POST);
$errors = [];
$target_dir = 'F:\wamp64\www\blank\dev\uploads/';
$extensions = ['pdf', 'PDF'];
$all_files = count($_FILES['file']['tmp_name']);
for ($i = 0; $i < $all_files; $i++) {
$file_Name = $_FILES['file']['name'][$i];
$file_Tmp = $_FILES['file']['tmp_name'][$i];
$file_Type = $_FILES['file']['type'][$i];
$file_Size = $_FILES['file']['size'][$i];
$tmp = explode('.', $_FILES['file']['name'][$i]);
$file_ext = strtolower(end($tmp));
$file = $target_dir . date('U')."-".basename($file_Name);
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_Name . ' ' . $file_Type;
}
if ($file_Size > 9000000000000000000) {
$errors[] = 'File size exceeds limit: ' . $file_Name . ' ' . $file_Type;
}
move_uploaded_file($file_Tmp, $file);
if ($errors) print_r($errors);
}
// Process to DB
Currently, the only data I can find is the formData from the form itself. If there is any information that I missed that could be helpful just let me know. Either I need to go about this a different way or I'm just missing something.
Any help is appreciated. Thank you.

PHP MySQL jQuery Uploading Multiple Files to server issue

I just finished designing a basic site to upload some files to the server, and store the file names in a database for searching functions. I designed the site using the following tutorial: www.formget.com.
My problem is when I go to upload more than one file at a time, it appends the filenames together for a single file.
Example:
Filename Example
Here is my code for uploading the files:
$error = '';
if(isset($_POST['submit']))
{
$j = 0; // Variable for indexing uploaded image.
$target_path = 'uploads/'; // Declare path for uploaded images.
for($i = 0; $i < count($_FILES['file']['name']);$i++) // Loop to get individual element from the array.
{
$valid_ext = array('jpeg','jpg','png','gif'); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_ext = end($ext); // Store extensions in the variable.
$filename = md5(uniqid());
$target_path = $target_path . $filename . '.' . $ext[count($ext) - 1]; // Set the target path with a new name of image.
if(($_FILES['file']['size'][$i] < 5000000) // Approx. 5MB files can be uploaded.
&& in_array($file_ext,$valid_ext))
{
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path))
{
// If file moved to uploads folder.
$success .= '<p class="success">('.$j.') Image uploaded successfully.</p>';
$date = date('Y-m-d H:i:s');
$stmt = $db->prepare('INSERT INTO uploads (filename,postdate,userid) VALUES (?,?,?)');
if($stmt)
{
$image = $filename . '.' . $ext[count($ext) - 1];
$stmt->bind_param('sss',$image,$date,$_SESSION['id']);
if($stmt->execute())
{
$success .= '<p class="success">('.$j.') Image added to database successfully.</p>';
}
else
{
$error .= '<p class="error">Error 34. Please contact the Site Administrator.</p>';
}
}
else
{
$error .= '<p class="error">Error 30. Please contact the Site Administrator.</p>';
}
}
else
{
$error .= '<p class="error">('.$j.') Please Try Again!</p>';
}
}
else
{
$error .= '<p class="error">('.$j.') Invalid file size or type.</p>';
}
$j = $j + 1; // Increment the number of uploaded images according to the files in the array.
}
}
Here is the jQuery:
var abc = 0; // Declare and define global increment value.
$(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: 'file[]',
type: 'file',
id: 'file'
}), $("<br/><br/>")));
});
// Following function will execute on change event of file input to select different file.
$('body').on('change', '#file', function()
{
if(this.files && this.files[0])
{
abc += 1; // Increment 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: '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();
}
});
});
Any input as to why it keeps appending the filenames together would be appreciated. Please note that in the database, the filenames are correct, just not on the server itself in the uploads directory.
You are not resetting $target_path inside your for loop and therefore string concatenating it while looping. Results will be like A, AB, ABC, ... This is the issue:
$target_path = $target_path . $filename . '.' . $ext[count($ext) - 1];
You could create two variables.
$target_path = 'uploads/';
outside of your for-loop and use something like
$move_to_target = $target_path . $filename . '.' . $ext[count($ext) - 1];
inside your for-loop and update your call of move_uploaded_file to pass $move_to_target instead of $target_path. Your database entries are not affected because you build up the filename again in $image - this however seems bad practice (redundant code), if you want to enhance your code define $image first and then create $move_to_target like this:
$move_to_target = $target_path . $image;

How to return File Path in Html of Gulp s3 Upload?

I'm creating an image optimiser using gulp and PHP for the Upload.
I want to be able to output the file path url of the uploaded file into index.php what is the best way to do it..
i've tried mimicking the output of the file path using the below, but didn't work..
-: print 'https://footpatrol.s3.amazonaws.com/images/'.date('Y').'/'. date('d-m').'/'.$newfilename.'';
PHP Code.
<?php
$files = glob('images/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
foreach($_FILES['file']['name'] as $index=>$name){
$filename = $name;
if(!file_exists("images/".$filename)){
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$newfilename = md5($file_basename) . $file_ext;
move_uploaded_file($_FILES["file"]["tmp_name"][$index],"images/" . $newfilename);
if( move_uploaded_file($_FILES["file"]["tmp_name"][$index],"images/" . $newfilename)){
print '<div class="img">https://footpatrol.s3.amazonaws.com/images/'.date('Y').'/'. date('d-m').'/'.$newfilename.'</div>';
}
}
}
?>
Gulp Code..
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var clean = require('gulp-clean');
var s3 = require('gulp-s3');
var AWS = require('aws-sdk');
var fs = require('fs')
var pngquant = require('imagemin-pngquant');
var jpegrecompress = require('imagemin-jpeg-recompress');
var moment = require('moment');
var runSequence = require('run-sequence');
// Delete files in image folder
gulp.task('cleanTemp', function(cb) {
return gulp.src('dist/images/*', { read: false }).pipe(clean());
cb(err)
});
// Delete files in image folder
gulp.task('delete', ['image'], function() {
return gulp.src('./images/*', { read: false })
.pipe(clean());
});
var year = moment().format('YYYY');
var today = moment().format('MM-DD');
// // Image Optimisation
//console.log('dist/images/'+year+'/'+today)
gulp.task('image',['cleanTemp'], function() {
return gulp.src('images/*')
.pipe(imagemin([
imagemin.gifsicle({ interlaced: true }),
jpegrecompress({
progressive: true,
max: 70,
min: 55
}),
pngquant({ quality: '70-80' })
]))
.pipe(gulp.dest('dist/images/' + year + '/' + today + ''));
});
aws = JSON.parse(fs.readFileSync('./aws.json'));
// // UPLOAD
gulp.task('upload', function() {
return gulp.src('./dist/**')
.pipe(s3(aws))
});
// Watch Image files
gulp.task('watch', function() {
gulp.watch('images/*', function(event) {
runSequence('cleanTemp', ['image','upload']);
});
});
// Default Task
gulp.task('default', ['cleanTemp','image', 'upload']);

How to overcome getClientOriginalName() error in Laravel dropzone file upload?

I am using Laravel 5.0, for image uploading I am using dropzone.js. Actually file uploading to folder and database but it is throwing error like
Call to a member function getClientOriginalName() on a non-object
on post method.
Where have I gone wrong?
View File,
<form method="POST" class="dropzone dz-clickable" id="productDropzone" action="{{url()}}/cms/website/pages/upload_files" enctype="multipart/form-data">
<div class="dz-default dz-message">
<span>Drop files here to upload</span>
</div>
<input name="_token" type="hidden" value="{{ csrf_token() }}">
<input type="submit" value="Upload" id="submit_all"/>
</form>
Below is my js,
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("form#productDropzone", {
paramName : 'file',
maxFilesize: 3, // MB
maxFiles: 3,
autoProcessQueue: false,
addRemoveLinks: true,
init: function() {
this.on("addedfile", function(file) { fileupload_flag = 1; });
this.on("complete", function(file) { fileupload_flag = 0; });
},
accept: function(file, done)
{
var re = /(?:\.([^.]+))?$/;
var ext = re.exec(file.name)[1];
ext = ext.toUpperCase();
if ( ext == "JPG" || ext == "JPEG" || ext == "PNG" || ext == "GIF" || ext == "BMP")
{
done();
}else {
done("Please select only supported picture files.");
}
},
success: function( file, response ) {
obj = JSON.parse(response);
file.previewElement.querySelector("file").src = obj.src;
// alert(obj.src);return false;
}
});
$('#submit_all').click(function(){
myDropzone.processQueue();
});
Controller function,
$com_id = Auth::user()->company_id;
$file = Request::file('file');
$destinationPath = public_path() . '/images/section/';
$filename = strtolower($file->getClientOriginalName());
$upload_success = $file->move($destinationPath, $filename);
if ($upload_success) {
$upload = new Cms_banner_master();
$upload->product_banner = json_encode($filename);
$upload->company_id = $com_id;
$upload->home_banner ="1";
$upload->save();
return Response::json(array($fileName));
} else
{
return Response::json('error', 400);
}
If you want to prevent the error from happening, you can add some validity checks on the file first.
For example with the isValid method
Update: I added the hasFile method too.
if(Request::hasFile('file') {
$file = Request::file('file');
if($file->isValid()) {
$destinationPath = public_path() . '/images/section/';
$filename = strtolower($file->getClientOriginalName());
$upload_success = $file->move($destinationPath, $filename);
if ($upload_success) {
...
}
}
} else {
return Response::json('No file uploaded', 409);
}
And I would also generate a new name for the uploaded file, this way you don't need the getClientOriginalName:
$filename = $com_id.'_'.date('YmdHis')'.'.$file->guessExtension();
In the spirit of "never trust the users" and not letting them 'choose' a file name from a file that you will be saving on your server.

php jquery image upload

i have a script that uploads an image into a folder instead of saving it as a blob..
<?php
mysql_connect('localhost','root','')or die(mysql_error());
mysql_select_db('db_tourism')or die(mysql_error());
//$newname='baro.jpg';
//dir:[../../]
$uploaddir = '../../images/municipality/';
$cc=$uploaddir.$fileName;
$fileName = $_FILES['uploadfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$ext = end(explode('.', $fileName));
$newname=$fileName;//.'.'.$ext;
$file = $uploaddir .$newname; //basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
// echo "<script>alert('success:$fileName');</script>";
mysql_query("INSERT INTO `_temp-image` ( `id` , `File_name` , `path` )
VALUES (
NULL , '$fileName', '$file'
);");
echo "success";
}
else {
echo "error";
}
?>
and here is the jquery
var btnUpload=$('#uploada');
//var btnUploadTxt=$('#uploada').attr('value');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
btnUpload.val('Only JPG, PNG or GIF files are allowed');
return false;
}
btnUpload.val('Uploading...');
},
onComplete: function(file, response){
//On completion clear the status
btnUpload.val('Upload Picture');
//Add uploaded file to list
if(response==="success"){
$('<li class="uplod" uid="_temp-image" title="click to remove ['+file+']" id="'+file+' "><span id=" '+file+' " style="font- family:calibri;font-size:10px;" >'+file+' [UPLOADED]</span></li>').appendTo('#uploaded');/ *.html('<img src="../uploaded_image/'+file+'" alt="" />'+file)*///.addClass('success');
} else{
$('<li></li>').appendTo('#uploaded').text(fi le).addClass('error');
}
}
});
it works fine i can add and delete picture... BUT my problem is handling DUPLICATE files... how to error trap if that kind of image is already uploaded??
Generate CRC checksum, MD5 or other hash type for image binary data and store that hash in database.
After upload - check new image checksum/hash and compare it with that stored in database.
Use md5_file function.
$md5hash = md5_file(string $filename);
Here is more: http://www.php.net/manual/en/function.md5-file.php

Categories