DropzoneJS has been around for a couple of years now, and various features can be used in clever ways. I wanted here to share with you a full example with DropzoneJS and what you can do with it, made nice and easy including the PHP function to handle the file upload and delete from server.
For those who didn’t hear about it, DropzoneJS is an open source library that provides dragβnβdrop file uploads with image previews.
Itβs lightweight, doesnβt depend on any other library (like jQuery) and is highly customizable.
You can read it’s docs on their website http://www.dropzonejs.com/
Upload files to your server with drag and drop.
Well commented and organized Javascript and PHP code that lights your way.
Thumbnails.
PHP validation that handles:
Upload or delete files.
Check if the upload folder exists and if we can write on it, and if there is any file with the same name.
Be sure that the file has been uploaded.
While deleting the previously uploaded file, check the directory’s permissions, check if the file exists, then delete the file, be sure we deleted the file.
Messages translations.
Custom preview for uploaded files.
And it’s responsive.
Of course, you should get the latest version of DropzoneJS http://www.dropzonejs.com/ and include in your project
In our example, I’m using Bootstrap, Font Awesome and jQuery, but they are not necessary.
There is a lot of unnecessary HTML code in our example, it’s just to look better.
<form action="file-upload.php" class="dropzone files-container">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
initFileUploader: function(base, target) {
var previewNode = document.querySelector("#onyx-dropzone-template"), // Dropzone template holder
warningsHolder = $("#warnings"); // Warning messages' holder
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
var onyxDropzone = new Dropzone(target, {
url: ($(target).attr("action")) ? $(target).attr("action") : "../../file-upload.php", // Check that our form has an action attr and if not, set one here
maxFiles: 5,
maxFilesize: 20,
acceptedFiles: "image/*,application/pdf,.doc,.docx,.xls,.xlsx,.csv,.tsv,.ppt,.pptx,.pages,.odt,.rtf",
previewTemplate: previewTemplate,
previewsContainer: "#previews",
clickable: true,
createImageThumbnails: true,
/**
* The text used before any files are dropped.
*/
dictDefaultMessage: "Drop files here to upload.", // Default: Drop files here to upload
/**
* The text that replaces the default message text it the browser is not supported.
*/
dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", // Default: Your browser does not support drag'n'drop file uploads.
/**
* If the filesize is too big.
* `{{filesize}}` and `{{maxFilesize}}` will be replaced with the respective configuration values.
*/
dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.", // Default: File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.
/**
* If the file doesn't match the file type.
*/
dictInvalidFileType: "You can't upload files of this type.", // Default: You can't upload files of this type.
/**
* If the server response was invalid.
* `{{statusCode}}` will be replaced with the servers status code.
*/
dictResponseError: "Server responded with {{statusCode}} code.", // Default: Server responded with {{statusCode}} code.
/**
* If `addRemoveLinks` is true, the text to be used for the cancel upload link.
*/
dictCancelUpload: "Cancel upload.", // Default: Cancel upload
/**
* The text that is displayed if an upload was manually canceled
*/
dictUploadCanceled: "Upload canceled.", // Default: Upload canceled.
/**
* If `addRemoveLinks` is true, the text to be used for confirmation when cancelling upload.
*/
dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", // Default: Are you sure you want to cancel this upload?
/**
* If `addRemoveLinks` is true, the text to be used to remove a file.
*/
dictRemoveFile: "Remove file", // Default: Remove file
/**
* If this is not null, then the user will be prompted before removing a file.
*/
dictRemoveFileConfirmation: null, // Default: null
/**
* Displayed if `maxFiles` is st and exceeded.
* The string `{{maxFiles}}` will be replaced by the configuration value.
*/
dictMaxFilesExceeded: "You can not upload any more files.", // Default: You can not upload any more files.
/**
* Allows you to translate the different units. Starting with `tb` for terabytes and going down to
* `b` for bytes.
*/
dictFileSizeUnits: {tb: "TB", gb: "GB", mb: "MB", kb: "KB", b: "b"},
});
Dropzone.autoDiscover = false;
onyxDropzone.on("addedfile", function(file) {
$('.preview-container').css('visibility', 'visible');
file.previewElement.classList.add('type-' + base.fileType(file.name)); // Add type class for this element's preview
});
onyxDropzone.on("totaluploadprogress", function (progress) {
var progr = document.querySelector(".progress .determinate");
if (progr === undefined || progr === null) return;
progr.style.width = progress + "%";
});
onyxDropzone.on('dragenter', function () {
$(target).addClass("hover");
});
onyxDropzone.on('dragleave', function () {
$(target).removeClass("hover");
});
onyxDropzone.on('drop', function () {
$(target).removeClass("hover");
});
onyxDropzone.on('addedfile', function () {
// Remove no files notice
$(".no-files-uploaded").slideUp("easeInExpo");
});
onyxDropzone.on('removedfile', function (file) {
$.ajax({
type: "POST",
url: ($(target).attr("action")) ? $(target).attr("action") : "../../file-upload.php",
data: {
target_file: file.upload_ticket,
delete_file: 1
}
});
// Show no files notice
if ( base.dropzoneCount() == 0 ) {
$(".no-files-uploaded").slideDown("easeInExpo");
$(".uploaded-files-count").html(base.dropzoneCount());
}
});
onyxDropzone.on("success", function(file, response) {
let parsedResponse = JSON.parse(response);
file.upload_ticket = parsedResponse.file_link;
// Make it wait a little bit to take the new element
setTimeout(function(){
$(".uploaded-files-count").html(base.dropzoneCount());
console.log('Files count: ' + base.dropzoneCount());
}, 350);
// Something to happen when file is uploaded, like showing a message
if ( typeof parsedResponse.info !== 'undefined' ) {
console.log(parsedResponse.info);
warningsHolder.children('span').html(parsedResponse.info);
warningsHolder.slideDown("easeInExpo");
}
});
}
Now the important part of the Javascript is these DropzoneJS options:
maxFiles: 5
maxFilesize: 20
acceptedFiles: “image/*,application/pdf,.doc,.docx,.xls,.xlsx,.csv,.tsv,.ppt,.pptx,.pages,.odt,.rtf”
previewTemplate: previewTemplate
previewsContainer: “#previews”
clickable: true
And it’s plain English π, it doesn’t need an explanation.
You can go through the lines and read my comments, I tried to make everything simple.
For more options, you can read the docs on http://www.dropzonejs.com/
/**
* Dropzone PHP file upload/delete
*/
// Check if the request is for deleting or uploading
$delete_file = 0;
if(isset($_POST['delete_file'])){
$delete_file = $_POST['delete_file'];
}
$targetPath = dirname( __FILE__ ) . '/uploads/';
// Check if it's an upload or delete and if there is a file in the form
if ( !empty($_FILES) && $delete_file == 0 ) {
// Check if the upload folder is exists
if ( file_exists($targetPath) && is_dir($targetPath) ) {
// Check if we can write in the target directory
if ( is_writable($targetPath) ) {
/**
* Start dancing
*/
$tempFile = $_FILES['file']['tmp_name'];
$targetFile = $targetPath . $_FILES['file']['name'];
// Check if there is any file with the same name
if ( !file_exists($targetFile) ) {
move_uploaded_file($tempFile, $targetFile);
// Be sure that the file has been uploaded
if ( file_exists($targetFile) ) {
$response = array (
'status' => 'success',
'file_link' => $targetFile
);
} else {
$response = array (
'status' => 'error',
'info' => 'Couldn\'t upload the requested file :(, a mysterious error happend.'
);
}
} else {
// A file with the same name is already here
$response = array (
'status' => 'error',
'info' => 'A file with the same name is exists.',
'file_link' => $targetFile
);
}
} else {
$response = array (
'status' => 'error',
'info' => 'The specified folder for upload isn\'t writeable.'
);
}
} else {
$response = array (
'status' => 'error',
'info' => 'No folder to upload to :(, Please create one.'
);
}
// Return the response
echo json_encode($response);
exit;
}
// Remove file
if( $delete_file == 1 ){
$file_path = $_POST['target_file'];
// Check if file is exists
if ( file_exists($file_path) ) {
// Delete the file
unlink($file_path);
// Be sure we deleted the file
if ( !file_exists($file_path) ) {
$response = array (
'status' => 'success',
'info' => 'Successfully Deleted.'
);
} else {
// Check the directory's permissions
$response = array (
'status' => 'error',
'info' => 'We screwed up, the file can\'t be deleted.'
);
}
} else {
// Something weird happend and we lost the file
$response = array (
'status' => 'error',
'info' => 'Couldn\'t find the requested file :('
);
}
// Return the response
echo json_encode($response);
exit;
}
Download our working example or view demo from the buttons at the beginning of this post.
Please don’t hesitate to write to me if something went wrong with you π I’m always glad to help.
The demo here is not really uploading any files to our server, it’s just for testing purposes.
Jamie Brooks
WroteHi Obada. This is a really great tutorial on how to use Dropzone js with PHP. Your comments were great. Very helpful and clear. I would like to have a small thumbnail appear in the ‘uploaded files’ preview area instead of just showing the file name. Would you be able to steer me in the right direction on how to do that by modifying your script? I’d like to show the file count in the directory as well if possible. Cheers!
admin
Replied to Jamie BrooksHi Jamie, I’m glad you like my post π
For some reason I don’t know, notification emails are coming late for me, so today I saw your comment…
I’ll try to add thumbnail feature to it and reply you the result
admin
Replied to Jamie BrooksIt’s done π
You can download a new version of the demo file
Have a nice day
Brano Cerny
WroteHi Obada,
Thanks for the great example.
I am not sure if there is a glitch in the script: after uploading the image for example the blue progress bar is still moving and never disappear (even the file is already on the server). It behave same way on your demo page. By looking at the script, it should show some message after the upload is complete or if the file exists already. Thank you. π
admin
Replied to Brano CernyHi Brano,
I’m sorry that the design wasn’t clear enough, this line is supposed to behave like this π¬, it’s just a demo or a snippet you can develop as your project requires, I didn’t take care about the warnings and messages…
feel free to ask me if you need anything π
Peter
WroteGreat tutorial! By far the best I could find. Thanks!
However… I downloaded the demo and found out that I have 3 problems with it.
1. Multi upload most of the time doesn’t upload all the files.
2. File renaming during upload doesn’t work. Same filenames are simply overwritten.
3. File delete does not erase the actual file from the hard drive.
Could you plz have a look at this?
Thank you! Have a nice day!
admin
Replied to PeterI’m very glad you liked it, you’re welcome.
Actually, I tried this demo on my server and it works smoothly and deletes the file, so do you think that your problem can be from your directory’s permissions? are you sure it does have the correct permission, so the script can upload the file
And for the file renaming, I didn’t look at it, because it’s used when you’re saving your files somewhere in the database but in my example, I didn’t use such a thing.
Send me your project’s link and I’ll be glad to help π
Mike
WroteSuper tutorial, Obada!
Works right out of the box.
How would it work if, say, somebody uploads a PDF to show a PDF icon?
admin
Replied to MikeThanks, I’m glad you like it.
I’m working on it, I did a revision now and it’s adding a .type-pdf (type-*filetype) class to the object’s preview container, if you can write CSS, you can continue from here. π
admin
Replied to MikeIt’s ready now, you can look at how it’s done and if you want you can support more file types, I made just 4 or 5 ones
Steven Pearson
WroteWould it be possible with this to list the files already uploaded?
admin
Replied to Steven PearsonIt’s possible as I think, you can check the previously uploaded files in the database and make a loop on the preview template.
Also there are some useful methods built in Dropzone for this, I googled it and I found useful links
https://stackoverflow.com/questions/17759286/how-can-i-show-you-the-files-already-stored-on-server-using-dropzone-js
https://www.startutorial.com/articles/view/dropzonejs-php-how-to-display-existing-files-on-server
https://gist.github.com/MarcoGomesr/6045401
Have a nice day, and if you do it, don’t forget to share it π
Steven Pearson
WroteThanks for your advise on existing files. I managed to make it work with Mock files. Is there a reason you chose such an old version of Jquery? It doesn’t work correctly with the current version. The UI is standard dropzone.
admin
Replied to Steven PearsonActually, there no specific reason for using it, it was in the project and I didn’t notice it’s so old π
Brian
WroteIs there a way to have this also populate previously uploaded files from an earlier session? it the folders contents with the delete option? I need to be able to manage the files in the folder and see whats there before i upload.
admin
Replied to BrianHello Brian,
You can achieve this but it’s not that easy, first, you have to pull the previously uploaded files from your database and print them in the Dropzone preview template area, then you’ve to edit the deletion code to make also delete the record from your database… actually it needs some work π
Regards
anthony
WroteThanks, this was very easy to configure and get working!
admin
Replied to anthonyThank you, I’m glad you like it π
Ednei Dias Peniche
WroteThe demo download is not working.
admin
Replied to Ednei Dias PenicheThanks for reporting this, I uploaded the file again, please try now…
Samo
WroteGreat example thanks. I’ve added some additional PHP file extension validation to secure against Javascript validation being bypassed, other than that all worked well. However, I’d like to add multiple dropzones to a single web page as our users are required to categorise certain images on upload. I’ve tried a few things but I’m not that experienced with Javascript. Could you please recommend the best way of implementing multiple dropzones into your example? Thanks
admin
Replied to SamoHello Samo,
I’m glad you found my post useful.
Usually, Dropzone does support multiple instances but I think the problem will be with PHP, you should implement the code and add a unique parametre for each form to separate between them in PHP, I will try to make a working example and email it to you
Regards
Ming
WroteYour code helps me a lot, thanks.
I am not sure if I am doing correctly, I found the code ‘info’ => ‘Successfully Deleted.’ , however I click to delete it, no such message is shown . Even I don’t create folder “uploads”, there is no error message “No folder to upload to :(, Please create one.” as well. Could you please help?
admin
Replied to MingHello Ming,
I’m glad you liked my code and used it.
The messages in the PHP file doesn’t show on the front-end, I wrote them just to check, and you can see them from the Chrome Dev Tools->Network->XHR
If you need any help don’t hesitate to contact me π
Ming
Replied to adminThanks for your reply.
Would you teach me how can I show message in front-end according to the upload result? e.g. Successfully Deleted, File too big?
admin
Replied to MingHello again Ming,
I’ve made a new version especially for you, feel free to download the files again from the download button at the beginning of this article…
And by looking at the JS code you’ll figure it out, I’ve just made a container for the messages in the index.html file, then gave it a little styling with CSS, then I appended the PHP messages that came with the Ajax response in it on Dropzone success and showed it.
Regards
Ming
Replied to adminOh, I found that my browser cached so that I didn’t see your reply, and re-post to here again, sorry about it.
Really appreciate and thanks a lot for your help & teaching. I will try it ASAP.
admin
Replied to MingYou’re welcome, I’m glad I was able to help.
And tell me if it worked for you
Ming
Replied to adminThank you Obada π
After fixing below syntax error in file-upload.php (line 41-42), it works fine and I can do what I want now, Thanks a million!
‘status’ => ‘success’,,
‘info’ => ‘Your file has been uploaded successfully.’
robert
WroteHello,
your code is perfect for my site thanks, I use it and everything goes well except for the progress bar that is not displayed, how can I do to display it?
admin
Replied to robertHello Robert,
Thank you, I’m glad you liked it.
Could you please share your website’s link with me so I can take a look?
robert
Replied to adminyes, I use your code on this page :
https://cs5.fr/boiteaplan.php?affaire=12789&action=suivant
admin
Replied to robertI think you’ve added a different version of the Dropzone’s CSS file, your CSS file shows this line (.dropzone .dz-preview .dz-progress) but actually, the progress bar is out of the .dropzone holder, so please take the CSS version from the demo I made or change the one you use, I mean this CSS file dropzonejs.css on your replace should be replace with this one dropzone.css from my demo
Don’t hesitate to write to me for more help π
robert
Replied to adminI have another problem, if I drop a large .zip file, the connection with the “file-upload” page is canceled after 30 seconds. how to make it work?
I add “application / zip” in acceptedFiles
admin
Replied to robertI think you have to edit your php.ini file, if you don’t have access to it you have to talk with your hosting provider.
Read more about this on:
https://stackoverflow.com/questions/578190/can-file-uploads-time-out-in-php
Or you have to make chunked uploads (which is much difficult). read about it here:
https://stackoverflow.com/questions/49769853/dropzone-js-chunking
Regards
robert
Replied to adminHello,
like Eric, the message info is not displayed on my page
admin
Replied to robertCould you please share your project’s link so I can take a look
robert
Replied to adminyou can see my project : https://cs5.fr/boiteaplan.php?affaire=12789&action=suivant
admin
Replied to robertYour JS code is missing this line
warningsHolder = $(“#warnings”); // Warning messages’ holder
You should place it under this one
var previewNode = document.querySelector(“#onyx-dropzone-template”);
But don’t forget to replace the semicolon at the end of the line with a comma π
robert
Replied to adminHi,
I have a new problem, with large files (over 200MB), I have his errors:
Server responded with 0 code.
and
413 Request Entity Too Large 413 Entity Request Too Large nginx
and here are my php config:
file_uploads: On
max_input_time: 120
memory_limit: 1000M
post_max_size: 1000M
upload_max_filesize: 1000M
admin
Replied to robertI’ve tried it on my website and it’s working with large files, so, are you sure that your server/localhost is taking configuration from the php.ini?
Some hosts ignore this file and go directly to their defaults.
Try to make a mistake in the php.ini file and see if your host will stay working or not, or look at the phpinfo()
Eric
WroteHello,
I find your project great and I use it on my site but I would like to delete the annimation on the progress bar and add the percentage?
thanks for your work
admin
Replied to EricHello Eric,
I’m glad you found it useful, just add the following lines to your CSS file to disable the progress bar animation:
.dz-preview:not(.dz-processing) .dz-progress {
animation: unset;
}
And for the percentage, you can read more about it here: https://stackoverflow.com/questions/38620641/how-to-show-upload-progress-percentage-in-dropzone-js
Eric
Replied to adminThanks for your help
I have another question regarding the message “info” return by file-upload that is not displayed on my frontend, how can I display it?
admin
Replied to EricYou’re welcome,
I don’t know if you have the latest version of my demo or not, because it wasn’t showing the messages returned by PHP on the frontend then I made an update on it, so please download it again now.
If your version is up to date, send me a link for your website and I’ll be glad to help
Domy
WroteHi! Great project it’s helping me a lot. Do you think it’s possible to make the photos sortable? Beginner here thanks if you got any time to help!
admin
Replied to DomyThanks Domy, I’m glad you like it.
Unfortunately, there is no easy way to do this. You’ve to integrate this JS library (https://sortablejs.github.io/Sortable/) with Dropzone.js’s preview template and save the order in your database.
You can search for some nice JS library for sorting elements if you didn’t like the one I sent.
Regards
hameed
WroteHello sir,
Thanks for the great work.
My question is how can we fetch previously uploaded images and display it in image preview-container. As I asked here (https://stackoverflow.com/questions/58256087/fetch-images-from-database-to-dropzone-js-plugin).
admin
Replied to hameedHello Hameed,
I’m glad you liked my work.
Actually I don’t think it’s easy to do but it’s not impossible, and I’m sorry now I don’t have the time to do it.
So I’ve got some good references for you and you can figure it out π
https://stackoverflow.com/questions/17759286/how-can-i-show-you-the-files-already-stored-on-server-using-dropzone-js
https://github.com/enyo/dropzone/issues/209
https://www.itsolutionstuff.com/post/how-to-display-existing-files-on-server-in-dropzone-js-using-phpexample.html
Rafael Ramos
WroteHi dude, great work!
Only to know how can i turn bigger the area for the DragN’Drop Files, cuz’ currently is really small
admin
Replied to Rafael RamosThanks, I’m glad you like it.
you just have to edit the CSS of the inner area (.files-container span), I’ve made it through padding, you can increase the paddings or give it a different CSS.
Regards
Rafael Ramso
Replied to admini’ve the issue with the width off the progress bar, i fix it, but now, the delete button icon it’s really on the right way, it’s possible to put it closer to the info of every file to upload?
admin
Replied to Rafael RamsoI couldn’t get your point, send me your project link so I can take a look
Rafael Ramos
Replied to adminOne more time it’s me!
Do you have the img thumbnail for the preview when it’s a XML file?
And if you have more of this thumbs, could you put the code?
admin
Replied to Rafael RamosYou can find more icons at https://flaticon.com, they have dozens of lovely free icons.
Also, I’ve got a nice files icons pack for you https://www.flaticon.com/packs/files-8
Rafael Ramos
Replied to adminHi man, thanks for your help, one more cuestion, there’s a way to make the progress bar a little bit smaller?
admin
Replied to Rafael RamosOf course, the progress bar is made by CSS, you can edit it
Rafael Ramos
Replied to adminHi man one more time here bringing problems.
My example was working well, but now i don’t know why sends me this when i try to upload a file:
“status”:”error”,”info”:”Couldn’t upload the requested file :(, a mysterious error happend.”
As i understand this error is for when the target to upload the files doesn’t exists, but in my case, it exists, so, i’m messing around with this
Do you’ve any idea for what’s happening?
admin
Replied to Rafael RamosHello Rafael,
I assume that the permission of the targeted folder is not correct, check it and make 755 through FTP or Cpanel, and tell me if it didn’t work, I’ll check it for you π
BTW, does my website sends a notification email when I reply to your comment?
Rafael Ramos
Replied to adminThanks for answering.
Yes, this sends me an email.
Well the permissions of this folder is 777, so it for all the permissions, i don’t think this is the problem
Actually set the permissions to 755 and this is the result:
{“status”:”error”,”info”:”The specified folder for upload isn’t writeable.”}
That’s why i put it on 777 again and it’s the same response of the previous comment
Rafael Ramos
Replied to Rafael Ramosi not using this example in a web site, i’m just doing it in my PC
i upload my code example pictures of the javascript file to a server
This files are named by numbers 1-4
this are the links of the images:
https://ibb.co/jJSqhsj
https://ibb.co/NWhR7jJ
https://ibb.co/VT3ZzpB
https://ibb.co/C5YpQLT
Rafael Ramos
Replied to Rafael RamosI’ve already solved this problem.
In my JS file, on the declaration of the Dropzone, i add a lines:
– uploadMultiple: true,
– parallelUploads: 100,
with this, the example doesn’t work.
And i’ve another question, let’s say, on the acceptedFiles i don’t have allowed to upload XML files
So how can i ignore those files?, Because right now if i’ve my maxFiles up to 10, and when i drag n’ drop a folder that contains a XML file, the upload gets interrupted because of that XML file.
admin
Replied to Rafael RamosI couldn’t find the relation between the inability to upload files and parallelUploads or uploadMultiple.
If you didn’t add a file type, you can’t then ignore it, you can define it from the beginning, add the .xml to acceptedFiles
Regards
Rafael Ramos
Replied to adminThanks man your help it’s great, and i understand that i can add XML to the acceptedFiles, but in the application that i’m planning to implement this dropzone there’s sort specific types of files that are allow, that’s the reason of my question, of how can i ignore these files, cuz’ right now when there’s one unaccepted, the upload stops.
admin
Replied to Rafael RamosAs I understand, you need to differentiate file types upon different user types or pages?!
Actually, you can make the accepted files as a variable and take the value from an attribute on dropzone’s form element.
Like this:
Define a new variable jus before var onyxDropzone = new Dropzone:
var acceptedFiles = $(target).attr(“data-accepted-types”);
Change acceptedFiles value:
acceptedFiles: acceptedFiles
Change HTML form tag:
Rafael Ramos
Replied to adminHi man it’s me again :v
I’m just having a problem with dropzone and firefox, this doesn’t work on firefox, do you’ve a solution for this=
admin
Replied to Rafael RamosYou can test my example with FireFox, it’s working like a charm. π
Rafael Ramos
Replied to adminHi Obada, thanks for all your help.
There’s a option that i’m thinking of this dropzone example, it’s possible that when i put my mouse pointer hover the thumb of an image, the thumb make it bigger?, to have a better preview of the img
admin
Replied to Rafael RamosYes you can add the following lines to your CSS code:
.thumb-container {
transition: transform .5s ease-in-out;
}
.onyx-dropzone-info:hover .thumb-container {
transform: scale(1.25);
}
Rafael Ramos
Replied to adminThanks man!, your idea is very helpful.
But maybe i don’t explain ass well as i think, i mean if there’s a way to make the thumb bigger, like opening a modal in the middle of the screen and give a bigger preview of only images, this is just for, lets say give to the user a way to confirm that the image is the real one to upload, to be sure of what it’s uploading
admin
Replied to Rafael RamosI got it, it’s not an easy thing to do.
You need to separate between images and files, also, integrate some nice way to show modals.
Rafael Ramos
Replied to adminOk man thaks for all your support… btw, now in my example, i got disabled, autoProcessQueue, this with the intention of use a button to upload the files, but let’s say, i upload 3 files and all of them are correctly uploaded, then i add one more file, and click on the upload button, and the dropzone, uploads all of the elements in there, even those ones that i’ve uploaded previously, there’s a way to control this? just to upload the new files
admin
Replied to Rafael RamosI’m glad you made what you wanted π
Actually, for the autoProcessQueue, I’ve no idea, I wish I could help
Rafael Ramos
Replied to adminHi man here again one more time.
Just question, how can i clear the Dropzone without deleting files from server?, just to clear the files that i already upload from the visual control in screen, or how can i add the control to a modal, and every time that the modal get’s closed, clear the dropzone, and once the modal is openned again the dropzone be able to work like normally
admin
Replied to Rafael RamosDo you mean that you want to upload and clear and then upload again on the same page without refreshing?
Rafael Ramos
Replied to adminHi man, well something like that, i’ve already solved this, maybe it’s not the best way, but right now works for me.
Question, there’s a way to show the files already stored in the server? And if it’s possible, can i manage those files direct from the dropzone, like deleting them?
admin
Replied to Rafael RamosHello again,
Of course you can manage the previously uploaded files and delete them or upload new ones but it depends on how you’ve managed to handle the uploaded ones at the beginning and you can integrate it with your code, but unfortunately, there are no ready scripts for this… maybe the following links can help you with it.
https://phppot.com/php/php-image-upload-using-dropzonejs/
https://www.codexworld.com/drag-and-drop-file-upload-using-dropzone-php/
https://www.cyblance.com/jquery/steps-implement-drag-drop-file-uploading-function-using-php-jquery/
Ramos
Replied to adminHi man here again, thanks for all your support.
Giving you problems again, now in my example ‘ve the control to same files, when theres one allready stored in my DB, i show the message in the dz-error class of the element in conflict, but i want to change the color of the process bar, because now this changes like the files is allready uploaded, so i want to change that color for more clarity for the final user, to they know that the file is not uploaded
Med Younes
WroteHello,
it’s a great work, thank you for sharing your experience.
But i found that MaxFile variable doesn’t work. Only, i can upload only 2 files in the same time
admin
Replied to Med YounesHello Med,
I’m glad you liked my work.
Maybe because you wrote maxFile not maxFiles, I’ve tried it and it was working fine.
If it didn’t work, please send me your project link and I’ll be glad to help π
Regards
Zarate
WroteHi, I’m trying to implement your fabulous code, but… Where is the “uploads” folder created?
I created it where file-upload.php is and it doesn’t work, I’ve read all the comments and surely I’m not doing something right. Could you help me?
Thank you!
admin
Replied to ZarateHello,
What is the error that you’re taking?
Did you see the console for any errors?
Regards
Zarate
Replied to adminThanks…
It doesn’t show me any error, it’s as if I didn’t get to file-upload.php, although the path is correct, just as I downloaded the code.
This is what I get in the console: http://prntscr.com/pt2utl
It’s got nothing to do with testing it at localhost, does it?
Zarate
Replied to adminI uploaded it to https://instalarwasap.com/media/ and it doesn’t work either.
Everything is as I downloaded it, I see that does not process anything file-upload, because if I delete the folder “uploads”, I do not skip error that it does not exist.
The content of the file “file-upload.php” is this:
https://instalarwasap.com/media/file-upload.txt
I hope you can help me, I really like this script for how light and practical it is. But I already have a couple of hours going around in my head π
admin
Replied to ZarateAs I see, you have a syntax error on line 41 in the file-upload.php
You’ve two commas there ‘status’ => ‘success’,,
and in the line under it, you didn’t put a comma at the end of it
Make these changes and upload it again if you have any error and I’ll be glad to check it.
Also, you’re using favicons from my website but through Http, I’ve updated it and now it should be Https, so please change all the URL’s from Http to https and you should see no errors π
admin
Replied to ZarateI forgot something, If you want to debug the upload ajax request you can see it in the developer tools>network, and you can see the error that came from file-upload.php in details
Zarate
Replied to adminI’m sorry to cause you so much trouble, you know… It’s weird about commas, because I didn’t touch anything but create the “uploads” folder. Even so, I’ve made the changes you’ve recommended and it still doesn’t work: http://prntscr.com/pt4r3i
I think it’s not getting to “file-upload.php”, maybe the error could be in scripts.js, but I don’t find it can be. The strange thing is that only I am having problems and without having touched anything. If you extract the zip and mount, it works perfect, right?
Well, thank you very much for your help and I will be attentive if someone else presents the error and manages to solve it.
Greetings!
admin
Replied to ZarateI think you have an older version, please download a new one now and everything should be fine π
Zarate
Replied to adminHello again, thank you so much for responding so quickly…
I downloaded it again and it didn’t work either. (the downloaded file “file-upload.php” presents the problem of the repeated commas you mentioned), I had a coffee and with a clearer mind, I started to compare line by line the downloaded scripts.js against the one you use in your demo, then I realized that line 61 of the downloaded file is like this:
var previewNode = document.querySelector(“#onyx-dropzone-template”);
The one you use is like this:
var previewNode = document.querySelector(“#onyx-dropzone-template”),
warningsHolder = $(“#warnings”);
Now everything works great.
Thank you very much for sharing your work, possibly complementing it with database!
Greetings!
admin
Replied to ZarateThank you for taking the effort and telling me about the commas, I’ve got it fixed.
I wish a good work.
Regards
Zarate
WroteThank you Obada, for your help. Wherever I use your work, I will certainly give you the credits. If I complement it with a database, I will tell you in case you want to include it.
Thank you very much… Success!
admin
Replied to ZarateIt will be great, you’re welcome π
Ramos
WroteHi man, i don’t know if there’s a limit of comments in this section, but only want to ask, how can i change the color of the progress bar depending of the response of dropzone when adding a file, let’s say my file allready is uploaded for my user, the function to DB response to me that is allready storage that file, but the progress bar gets like the file was uploaded, when that’s false, how can manage the color of the bar?
admin
Replied to RamosHi Ramos,
Sorry for the late reply but I was busy.
In order to change the progress bar color, you have to add a class to the preview item (. dz-image-preview), let’s say you added (.previously-uploaded) class, then you have to add the following lines to your CSS file:
.previously-uploaded .dz-progress .dz-upload {
background: red;
}
Ramos
Replied to adminHi man, never mind of the other comments i’ve already solved this.
i just add the class “dz-error” to the file.previewElement, then i look for the class “dz-upload” and i apply a direct .css background color change.
admin
Replied to RamosI’m glad you figured it out π
roman
WroteI want to double check the file. If there are duplicate files Can choose between overwrite upload and cancel upload Can I fix where?
admin
Replied to romanYou have to do it, I don’t think there is a ready script for this.
roman
Replied to romanI got a problem when uploading. It only works for 2 files. After that it doesn’t work. Where can i fix it?
Sorry to bother you too much Right now I’m working on a project. So I hurried to finish it in time.
https://cdn.discordapp.com/attachments/445397699928260610/648534523641856012/unknown.png
admin
Replied to romanYou have to change this (maxFiles: 5) in the scripts.js
ced
WroteHello,
thank you for your work that I just installed on my site.
Unfortunately, I can not use it for large files (800MB – 1GB), so I decided to do with the “chunked” function
but it does not work better.
do I change the settings for this item in dropzone.js?
I have these errors:
[Violation] ‘setTimeout’ handler took 13135ms
4541dropzone.js:2781 POST https://… net::ERR_INSUFFICIENT_RESOURCES
dropzone.js:2757 Retried this chunk too often. Giving up.
I have this configuration:
maxFilesize: 1024,
timeout: 0,
createImageThumbnails: true,
chunking: true,
forceChunking: true,
chunkSize: 100000,
parallelChunkUploads: true,
retryChunks: true,
retryChunksLimit: 3,
Do you know how I can solve my problem ?
admin
Replied to cedI’m glad you liked it.
Sorry but I didn’t work with chunk uploads before, but you may read more about it here:
https://stackoverflow.com/questions/49769853/dropzone-js-chunking
Terry Eelekes
WroteThank you for the code. I have a problem that it will not upload the file. file.upload-ticket shows undefined and even if there is no folder I am not getting a error back from the php page. every thing else great.
admin
Replied to Terry EelekesYou’re welcome, Could you please share a link for your project so I can see it?
Terry Elekes
Replied to adminFirst I tried in my project on my localhost and it would not work, so then I put the your code from the download source in my local server and that to has the same problems . I get all the errors from the jquery but never reaches the php file. Thanks for replying so quick.
Terry Eelekes
Replied to Terry ElekesPart of my problem the permission on the uploads folder. Now when I drop a file it states it was successful but no image in folder.
Ramos
WroteHi Obada it’s me again
Bro, how can i clear the added files area of the dropzone without deleting the files ?
Let’s say, on my page i have on a bootstrap modal 2 divs, the first with a jQuery Grid that shows me the files that i’ve already uploaded, and i’ve an add button, this hide the first div and shows the second, where i’ve the dropzone, and when i upload all the files, i’ve able a button to come back to the previous div and hides the one that contain the dropzone, but how can i “delete” or erase the files from the area, and not to delete them from the server?
admin
Replied to RamosHey Ramos,
You can just disable the Ajax call that is responsible for sending the deletion method to PHP and the files won’t be deleted actually π
Ramos
Replied to adminOk man i’ll try that, another question, if i’ve my maxFiles at 5 files as max, but when i drag and drop a folder with 15 files, right now of all the files only 4 were uploaded and 1 it’s marked like maxFileSize exceeded and all the remaining files gets market like i’ve
over passed the limit of files.
My question is why the dropzone doesn’t try to upload another file? skipping that is marked like maxFileSize
admin
Replied to RamosHey Ramos,
Have you figured this out?
Andy
WroteHello,
thanks for this useful tutorial and the great work you shared.
When I upload more than two documents the uploadbar appear only for the two first and then the other files are not uploaded.
Did you still experience this problem?
No meggage errors are displayed: the file are added to the list but without the blue uploaded bar.
Thank a lot
Andy
admin
Replied to AndyHey Andy,
I’m glad you liked my post.
The lines appear one by one, it just take some time to show, Dropzone handles two files at a time.
Do you have any errors in the console?
Andy
Replied to adminHello,
thanks.
I have no errors on the internet page and no message appear under the list (like “Just a test, don’t take it seriously.” as in your test page). Nor are displayed messages like
I experienced some issues:
– I see that in the page the uploaded files but the count remains 0. I tried with safari and firefox on mac.
– I can’t delete uploaded files by clicking the red x, the file disappear from the list but remain on server (folder set 775).
– if I add 3 or more files only the first 2 are correctly uploaded but the others are added to the list without the progress bar. If I add one more file the first 2 queued will be uploaded. Then see next point…
– I tried to add this line
warningsHolder = $(β#warningsβ); // Warning messagesβ holder
in JS file (like you suggested in one post). The result is that the dropped files are now displayed as icons in the dropzone but none appear in the list below. But in this case it is possible to upload more than 2 files at a time.
– I never see any messages at the bottom of the page
Thanks and have a nice day
Andy
admin
Replied to AndyCould you please provide a link to your project so I can help more.
Andy
WroteHello,
I finally got time to taka look to my project. I replaced, as you suggested in your e-mail, the project with a new downloaded copy. As a result I had sames problems (files count remain 0, no messages are displayed and max 2 files dowloaded).
I checked in the browser console and tried with the fresh installed copy and with your on site preview mode. I discovered that the errors occurred at different lines of the code of the script.js and that the two project behave different (on site good and the fresh copy not).
I solved by download the script.js running on your site and replacing the one present in the dowloaded project. Now the uploads behave good and the problems are solved.
But now the thumbnail don’t appear (only “document”), but this on your site too. This is not an issue for me but if you find a fix would be perfect.
Thank a lot for your help
Andy
admin
Replied to AndyI’m glad you figured it out π
David
WroteHello,
Thanks for your work on this !
Im having an issue : the count is not changing …
Im using same things but my index is a php page.
Other than that it’s uploading fine π
Thanks
admin
Replied to DavidHello David,
I don’t think it’s related to file type if it’s HTML or PHP. If you haven’t figured this out please share a link to your project with me and I’ll be glad to help
Jose Ruiz
Replied to Davidthe problem is that miss a line in the script.js after line 61
warningsHolder = $(“#warnings”);
the final code is from line 60 till 64 is
initFileUploader: function(base, target) {
var previewNode = document.querySelector(“#onyx-dropzone-template”), // Dropzone template holder
warningsHolder = $(“#warnings”); // Warning messages’ holder
previewNode.id = “”;
best
Fidajo Bonkeris
WroteThank your for this cool tutorial. Can you please tell me how to change the filename of the files with inputfields. You use span to Show the Name, can we use somehow there a inputfield ? I hope to become an answer
admin
Replied to Fidajo BonkerisHello Fidajo,
You can start implementing this by creating an input field and pass its value to file-upload.php and update this line ($targetPath . $_FILES[‘file’][‘name’];), but, then you’ll have to validate the inserted name and check for symbols or characters that can’t be used in filenames!!
It’s a little bit tricky, I wish I could help but I’m extremely busy in the meantime π
brian
Wrotethank you so much for this great script it has proven very useful for the project I am currently working on, I have been trying to add an upload successful message but so far have had no luck, could you possibly point me in the right direction?
admin
Replied to brianHello Brian,
Actually it does show a message in (warningsHolder) the message is coming from file-upload.php with the returned object.
You can see it in the demo but here it says (Just a test, don’t take it seriously.), if it was a success it will be (Your file has been uploaded successfully.)
Ryan
WroteHi, thank you for your work!
However I have encountered a problem when upload some files (with same extension without corrupted).
…
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse ()
…
in script.js(let parsedResponse = JSON.parse(response);)
May I know is there a solution for it? Thank you.
admin
Replied to RyanSorry for the late reply and I hope you figured it out.
You can solve this by wrapping JSON.parse in a try/catch block to prevent any errors that could stop the JavaScript execution.
patrice
WroteHello, Great job but when downloading example there’s an error in the file scripts.js at line 61-62, you should have:
var previewNode = document.querySelector(“#onyx-dropzone-template”),
warningsHolder = $(“#warnings”); // Warning messages’ holder
the second part isn’t there in actual file.
admin
Replied to patriceThanks for letting me know, it seems like I forgot to upload the new version π.
Julian
WroteHi! The first codeline
initFileUploader: function(base, target) {
returns the following error
“SyntaxError: Function statements require a function name”
What I’m missing?
admin
Replied to JulianHi Julian,
Have you downloaded the demo code or you copy-pasted the code on this page?
If you take it from the code here on this page it won’t work, I used object style in my code, so actually initFileUploader is an object key and its value is an anonymous function.
Hope this makes any sense
Julian
Replied to adminNow is working, thank you so much.
I was running out the time, never saw the download bottton.
Great work! Thank you again
Lance
WroteHi Obada!
Sort of a random question and if you would rather not respond I totally understand! I know there will likely be numerous potential settings causing the below behavior and with minimal information it may be difficult to help.
I use dropzone on a website to upload images, only allowing jpgs. There are multiple people who use the site on a daily basis to upload a lot of images.
There are a few users who intermittently get the error ‘Server responded with 0 code’.
The thing that’s frustrating is it seems to be completely random. For example a user could queue up 30 images, and maybe one or two will return with the error. Or perhaps they won’t have any errors at all that day. Or maybe a bunch of files will error. However it appears to happen to the same small subset of users.
I’ve been using the system daily myself to upload images since 2015 and haven’t had a single issue. So it has been very difficult for me to find the root cause, as I can’t duplicate it myself.
The system runs on Ubuntu/nginx/php7.3-fpm/mysql. I check the logs and can never find anything that would lead me to a potential solution.
Would there be anything you could think of debug wise, that would potentially lead me in a direction of resolving the issue?
Thank you!
admin
Replied to LanceHello Lance,
As I can imagine the problem is related to your host because it doesn’t make sense that you can’t reproduce the issue or it’s happening randomly.
and you’re not the only one who is experiencing the same issue, look at these links:
https://stackoverflow.com/questions/47826042/server-responded-with-0-code-issue-in-dropzone-js
https://www.prestashop.com/forums/topic/624940-any-ideas-what-error-server-responded-with-0-code-means-when-uploading-module/
Maybe you can try moving your project to a different host and test it for a couple of days.
Regards
name
Wrotehello admin i read your article very nice and helpful my project but i have a question when i upload dropzone file on my application i submit file on ajax method if any error occur file remove on dropzone i want file not remove because user confuse when user submit second attempt without upload file kindly communicate me it’s urgent thanks
admin
Replied to nameHello, I don’t seem to understand your question, could you please provide a link to your project so I can check?
Helge Schneider
WroteWow, that was awesome! Thank you so much, saved my day!!
Helge Schneider
WroteI updated your example to work with chunked file uploads as well, so the file size is not a limiting factor. Also did some bug fixing and displayed some more user messages. Please get in touch so I can send you the updated example! π
Michal Ivanic
Replied to Helge SchneiderHi Helge,
I plan to use this in one of my project, would you be willing to share the updated file via some git or share service? Thanks
Michal
admin
Replied to Michal IvanicI’ve sent it to your email through Wetransfer, please remember to download the file within 7 days.
Here is the download link https://we.tl/t-vpMtsJVIEI
Najwa Muhammad
Replied to adminHi Obada,
Could you share the updated file with me please?I need it in my project.
Thanks
admin
Replied to Najwa MuhammadHello,
Here it is
https://drive.google.com/drive/folders/1_Su3lGkUWDPIe9PgJedAop60vDhnv12z?usp=sharing
Mike
WroteI would like to use your code for personal use. Where can I obtain the complete source code? Mike.
admin
Replied to MikeJust download it from the download button at the beginning of this page.
Adept
WroteHello,
Currently when an error occurs (for example name already exists), the form will still display the file as if it was uploaded and will delete the already existing file if it was removed from the list. Is there a workaround to fix this issue?
admin
Replied to AdeptHello Adept,
Sorry but I’m no longer using Dropzone to handle uploads, either jQuery. But I think you have to catch the error event and remove the file that wasn’t uploaded.
Matti
WroteThank you very much for this example!
Could you you show us the example for adding multiple dropzones on a single web page? Would be Awesome!
Regards, Matti
admin
Replied to MattiHello Matti,
Youβre welcome, Iβm glad you like it.
Sorry but in the meanwhile, I donβt have the time to implement it, maybe this example could help.
https://gist.github.com/bennadel/7967676
Metin2
WroteHi, I uploaded the code on my site, but when I enter the browser and after uploading the image it tells me: No folder to upload to :(, Please create one.
Where should I create a folder?
admin
Replied to Metin2Hello Metin2,
You should create the folder on your host in the same path.
Steve
Wrotedownloaded the demo install and set it up on a web server and I’m getting errors:
Undefined index: target_file in /var/www/html/file-upload.php on line 86
admin
Replied to SteveHello Steve,
Something is wrong with your JavaScript code, “target_file” should be sent from JS to PHP.
I’ve added an extra check in the PHP code, you can download a new version of it.