How to upload multiple files using dropzone.js? - php

My problem is when I drag & drop multiple files that time each image is called a particular ajax. I want to multiple file upload time only one ajax call.
I want to choose a single file and drag & drop it in dropzone and another file drag & drop so as not to replace the file with to first one I need both theme and click on the button that time save in the folder at one time ajax call.
Here is my code
HTML file
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/min/dropzone.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.2.0/min/dropzone.min.js"></script>
<div class="row">
<form action="route.php?actionPresubmission=loanPreSubmission" class="form-horizontal dropzone" id="imageform">
</form>
</div>
route.php
$uploadDir = 'upload';
if (!empty($_FILES)) {
$tmpFile = $_FILES['file']['tmp_name'];
$filename = $uploadDir.'/'.time().'-'. $_FILES['file']['name'];
move_uploaded_file($tmpFile,$filename);
}
Thanks

Interpreting the question, I think you want to upload multiple files through one call.
For that, you need to stop autoProcessQueue which is true by default
Script:
Dropzone.options.myDropzone = {
autoProcessQueue: false, //This stops auto processing
acceptedFiles:".png,.jpg", //Change it according to your requirement.
init: function(){
var submit = document.querySelector('#submit');
mydropzone = this;
submit.addEventListener("click", function(){
mydropzone.processQueue();
});
this.on("success", function(file,response){
alert(response);
});
},
};
HTML:
<form action="upload.php" class="dropzone" id="myDropzone"></form>
<div>
<button type="button" class="btn btn-info" id="submit">Upload</button>
</div>
PHP
<?php
$folderName = 'upload/';
if(!empty($_FILES))
{
$file = $_FILES['file']['tmp_name'];
$fileLocation = $folderName . $_FILES['file']['name'];
move_uploaded_file($file,$fileLocation);
} ?>
Hope this helped you :)

Related

Drag and Drop Zone opening file instead of uploading to server

I have a file upload zone, one that let's you choose the file while the other is a drag and drop file upload zone.
Choosing file and clicking submit works perfectly fine.
The drag and drop zone however opens/downloads the file instead of uploading.
I think my PHP code is correct, because the file is getting correctly uploaded to server on choosing and uploading.
This is the JQuery code where I think there's a possible error.
+ function($) {
'use strict';
// UPLOAD CLASS DEFINITION
// ======================
var dropZone = document.getElementById('drop-zone');
var uploadForm = document.getElementById('js-upload-form');
var startUpload = function(files) {
console.log(files)
}
uploadForm.addEventListener('submit', function(e) {
var uploadFiles = document.getElementById('js-upload-files').files;
e.preventDefault()
startUpload(uploadFiles)
})
dropZone.ondrop = function(e) {
e.preventDefault();
this.className = 'upload-drop-zone';
startUpload(e.dataTransfer.items)
}
dropZone.ondragover = function() {
this.className = 'upload-drop-zone drop';
return false;
}
dropZone.ondragleave = function() {
this.className = 'upload-drop-zone';
return false;
}
}(jQuery);
Here's the HTML for a better reference:
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><strong>Upload CSV File</strong> <small>Insert Leads to MongoDB</small></div>
<div class="panel-body">
<!-- Standard Form -->
<h4>Select files from your computer</h4>
<form action="" method="post" enctype="multipart/form-data" id="js-upload-form">
<div class="form-inline">
<div class="form-group">
<input type="file" name="file" id="js-upload-files">
</div>
<button type="submit" class="btn btn-sm btn-primary" id="js-upload-submit">Upload files</button>
</div>
</form>
<!-- Drop Zone -->
<h4>Or drag and drop files below</h4>
<div class="upload-drop-zone" id="drop-zone">
Just drag and drop files here
</div>
</div>
</div>
I want the drag and drop zone to upload the file to server as well instead of opening.

Using Dropzone with Laravel 5.5

I would like to implement Dropzone in my long form. All tutorials focus on image upload ONLY, there are no tutorials if you have other stuff in your form. I am stuck in displaying dropzone. I have linked css and js files in my layout file but I still get an unstylized box for image upload and error in console: No URL provided.
This is a part of my form that should display Dropzone:
<form action="/ads/new" method="post" enctype="multipart/form-data">
<input class="input" type="text" name="name">
<input name="file" type="file" class="dropzone" multiple />
I would appreciate any help. Thanks.
UPDATE: I googled all the examples for this uploader and they all have only image upload field and nothing else. I need a solution when I have actually more fields in the form. Class dropzone can't be on whole form because I have more fields in it This is not just an image uploader!
I tried with this:
Dropzone.autoDiscover = false;
$("#pics").dropzone({
url: '/ads/new',
maxFilesize: 1
});
And there are no errors but whole dropzone functionality is gone.
Btw. If you don't know how to help then there is no need to downvote.
Try this might be help you
<form action="/ads/new" method="post" enctype="multipart/form-data" class="dropzone">
<input class="input" type="text" name="name">
<input name="file" type="file" multiple />
To make dropzone work in Laravel you can use the example below. Change it to your desired behaviour of course.
HTML
<form id="my-awesome-dropzone" class="dropzone"></form>
JQuery
<script type="text/javascript">
Dropzone.autoDiscover = false;
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var token = "{{ Session::token() }}";
$("#my-awesome-dropzone").dropzone({
paramName: 'file',
url: baseUrl+"/ads/new",
params: {
_token: token
},
dictDefaultMessage: "Drop or click to upload images",
clickable: true,
maxFilesize: 2,
addRemoveLinks: true,
removedfile: function(file) {
// #TODO : Make your own implementation to delete a file
},
queuecomplete: function() {
// #TODO : Ajax call to load your uploaded files right away if required
}
});
});
</script>
Laravel Upload Function for route: /ads/new
use Illuminate\Support\Facades\File; // Required Dependencies
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
public function upload() {
$destinationPath = public_path() . '/uploads/'; // upload folder, set whatever you like
$fileNameWithExtension = Input::file('file')->getClientOriginalName();
$upload_success = Input::file('file')->move($destinationPath, $fileNameWithExtension); // uploading file to given path
if ($upload_success) {
return Response::json('success', 200);
} else {
return Response::json('error', 400);
}
}

Combine normal form with Dropzone

I am creating a drop zone form using dropzone.js. I firstly set the form up to automatically upload the file this worked fine, but I adapted the form to work only when the user submitted the data, i added file called custom_dropzone.js and the form appeared to work but the files never got uploaded to the folder.
HTML CODE (index.php)
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<head>
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
<script src="dropzone.min.js"></script>
<script src="custom_dropzone.js"></script>
<!-- Now setup your input fields -->
<input type="email" name="username" />
<input type="password" name="password" />
<button type="submit">Submit data and files!</button>
</form>
</body>
</html>
upload.php
<?php
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = '../upload_test/uploads'; //2
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name']; //3
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //4
$targetFile = $targetPath. $_FILES['file']['name']; //5
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
echo 'error';
}
move_uploaded_file($tempFile,$targetFile); //6
}
?>
NEW JS custom.dropzone.js which seems to break the upload.php function
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 3,
maxFiles: 3,
previewsContainer: ".dropzone-previews",
accept: function(file, done) {
console.log("uploaded");
done();
},
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
});
},
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
thanks for a lll your help. I just need the file to be uploaded, every thing else seems to work fine
You forgot to add enctype='multipart/form-data' to your <form> as an attribute and the method type as POST.
Add like this..
<form id="my-awesome-dropzone" method='post' class="dropzone" action="upload.php" enctype='multipart/form-data'>
With dropzone it seems that you do not need
method='post'
enctype='multipart/form-data'
like what was mentioned by Shankar … but thank you
I resolved this by commenting out the below line of js from custom_dropzone.js
//uploadMultiple: true,

Uploading file via PHP in form

(beginner)
I'm having trouble uploading my file. I see the filename being posted to the database, but the file is not being posted to the images folder. It seems as though nothing is happening. Here is my following code, please advise me what I need to change:
<?php
//the $art variable gets posted to a database eventually
$art = mysql_real_escape_string(stripslashes($_FILES["art"]["name"]));
$art_ext = pathinfo($art, PATHINFO_EXTENSION);
$art = md5($art).".".$art_ext;
if($art!=""){
move_uploaded_file($art, "images/".$art );
}
?>
<script type="text/javascript">
$(function(){
image_upload = {
UpdatePreview: function(obj){
// if IE < 10 doesn't support FileReader
if(!window.FileReader){
// don't know how to proceed to assign src to image tag
} else {
var reader = new FileReader();
var target = null;
reader.onload = function(e) {
target = e.target || e.srcElement;
$("#imageupload").attr("src", target.result);
};
reader.readAsDataURL(obj.files[0]);
}
}
};
});
</script>
<form action="new.php" method="post" enctype="multipart/form-data">
<input type='file' name='art' id="file" onchange='image_upload.UpdatePreview(this)' value="Upload" accept="image/gif,image/jpeg,image/png"/>
</p>
<p>upload a image! (.gif, .jpg, .png formats allowed. 5MB max)</p>
<img id="imageupload" src="1x1.png" alt="test" />
<input type="submit" class="smallbtn4" style="cursor:pointer;" value="post"/>
</form>
Here's the format for move_uploaded_file():
$path = 'images/';
move_uploaded_file($_FILES['art']['tmp_name'], $path.basename($_FILES['art']['name']));
when using move_uploaded_files() your destination path should also include the name of the file....right now your destination path is:
images/
it should be:
images/nameOfImg.ext
Hope this helps!
EDIT:
After seeing the comment by #enhzflep, you should also hash the name of the file and create your filename string before using it in move_uploaded_file();

jQuery Fileupload and writing filename do MySQL database

I'm trying to create a file uploader with jQuery, that uploads a file, renames it with a timestamp and registers it into a DB. Basically it it sends the file with a form to the server where a second script renames it and moves the file to the right directory. This works without any problem. The problem is, that I want to send also the table name where this DB Entry should be made.
So index.php contains the form:
<div id="uploaderMain">
<p>Upload Your Files</p>
<form method="post" enctype="multipart/form-data" action="./upload.php">
<input type="file" name="images" id="images" />
<input type="hidden" name="List" id="List" value="<?php echo $DBTable; ?>" />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">
</ul>
</div>
The jQuery Code looks like this:
$.ajax({
url: "./uploader/upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
The upload.php looks like this:
<?php
//include db configuration file
include_once('../../db.php');
$List = $_POST['List'];
// get the time stamp for the uploaded file
date_default_timezone_set('EST');
$date = new DateTime();
$date = $date->getTimestamp();
// echo $date;
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
// store the file name and the file ending in 2 variables
$fileEnding = substr($name, -4,4);
$fileName = substr($name, 0, (strlen($name)-4));
$uploadName = $fileName."_".$date.$fileEnding;
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "./uploads/" . $uploadName);
}
}
after that I want to write to the DB. The problem is, that the $_POST['LIST'] statement doesn't provide my DBTable-name.
Can anyone give me a hint?
Cheers
Dan
I think you need to add this to your jQuery code:
formdata.append('List', '[your value]');
Please note: in PHP everything that is a file will go into $_FILES. Everything else will go into $_POST.
If this does not work, make sure you also have the following code:
var formdata = new FormData();
jQuery.each($('input[type="file"]')[0].files, function(i, file) {
formdata.append(i, file);
});
Can you check the source from browser if the List control has any value.

Categories