In this post, I will show you, how to upload files with drag and drop interface with dropzone.js in your Codeigniter framework applications.
Dropzone.js comes with nice CSS and Javascript that makes it a breeze to work with HTML 5 file upload API. It provides you with a file input container that users can drag and drop files unto or just click the container to select multiple files from the file system.
Supported Browsers?
Based on the plugin documentation Dropzone.js works in :
- Chrome 7+
- Firefox 4+
- IE 10+
- Opera 12+ (Currently disabled for MacOS because their API is buggy)
- Safari 5+
For all the other browsers, dropzone provides an old-school file input fallback.
How to implement in Codeigniter
1.First Download CodeIgniter, and setup locally. Then create a folder in application root folder(where index.php lives) for storing uploaded Files.
2. Download dropzone.js from https://github.com/enyo/dropzone, extract the zip copy all files from download folder, and place it in your resources folder(create folder just like uploads).
3. create a controller File called dropzone.php in controller dir then place the fallowing code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Dropzone extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper(array('url','html','form')); } public function index() { $this->load->view('dropzone_view'); } public function upload() { if (!empty($_FILES)) { $tempFile = $_FILES['file']['tmp_name']; $fileName = $_FILES['file']['name']; $targetPath = getcwd() . '/uploads/'; $targetFile = $targetPath . $fileName ; move_uploaded_file($tempFile, $targetFile); // if you want to save in db,where here // with out model just for example // $this->load->database(); // load database // $this->db->insert('file_table',array('file_name' => $fileName)); } } } /* End of file dropzone.js */ /* Location: ./application/controllers/dropzone.php */ |
4 Create a view File Called dropzone_view.php in views.Feed with bellow code
1 2 3 4 5 6 7 8 9 10 11 |
<html> <head> <link href="<?php echo base_url(); ?>resouces/css/dropzone.css" type="text/css" rel="stylesheet" /> <script src="<?php echo base_url(); ?>resouces/dropzone.min.js"></script> </head> <body> <h1>File Upload using dropzone.js and Codeigniter - arjun.net.in</h1> <form action="<?php echo site_url('/dropzone/upload'); ?>" class="dropzone" > </form> </body> </html> |
I hope this tutorial helps you please don’t forget to give us your feedback in comments.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.
Thank you so much! This tutorial will rly help me out with a problem i got on creating a gallery..! 🙂
you are welcome !
awesome tutorial Arjun. Helps me a lot ………
great tutorial ^_^
Thanks a lot ..
you are welcome ! keep reading
how to delete a uploaded file or cancel an upload.. can u just show that too
sure , next post i will write about it
hey arjun! that was really useful! actually i was reading your post on “adding mutiple files using ci”. and ended up here 🙂
just added to my project. btw can you tel me how to restrict files to specific types.
you can set acceptedFiles option ,Eg.: image/*,application/pdf,.psd. If
the Dropzone is clickable this option will be used as accept parameter
on the hidden file input as well.
you can also check server side using something like this
if ((($_FILES[“file”][“type”] == “image/gif”)||
($_FILES[“file”][“type”] == “image/jpeg”)|| ($_FILES[“file”][“type”] ==
“image/pjpeg”))) {
// do ..
}
or you can use
if(in_array($_FILES[“file”][“type”] ,array(“image/gif”,…))) {
// do
}
hi arjun after reading comment then i choose server side to prevent users uplaod another ekstentions but nothing working , please review me ? thanks
if ((($_FILES[“file”][“type”] == “image/gif”)||
($_FILES[“file”][“type”] == “image/jpeg”)|| ($_FILES[“file”][“type”] ==
“image/pjpeg”))) {
// i did insert here and also upload to folder
}
else
{
echo ” alert (‘wrong ekstention’); window.history.back();”;
}
hey arjun! that was really useful! actually i was reading your post on “adding mutiple files using ci”. and ended up here 🙂
just added to my project. btw can you tel me how to restrict files to specific types.
you can set acceptedFiles option ,Eg.: image/*,application/pdf,.psd. If the Dropzone is clickable this option will be used as accept parameter on the hidden file input as well.
yeah initially id dint work for me ..later i noticed i was linking my view file to minified js file.
you can also check server side using something like this
if ((($_FILES[“file”][“type”] == “image/gif”)||
($_FILES[“file”][“type”] == “image/jpeg”)|| ($_FILES[“file”][“type”] ==
“image/pjpeg”))) {
// do ..
}
or you can use
if(in_array($_FILES[“file”][“type”] ,array(“image/gif”,…))) {
// do
}
thanks alot!
but i figured out somethng else.
you can restrict file types by mentioning it inside “dropzone.js”
just have to set
//allowedfiletypes=”.jpg”
thats it!
and also change src link to dropzone.js instead of dropzone.min.js
hacking library file is not a good idea
in my knowledge(from github wiki-issues), those are changeable values
i follow the insrtuction but nothing helps, how can i prevent another ekstention if users upload wrong ekstention
thats not “hacking” they give you option to change. you can read the code comments
ey i can see the visual working but nothing is being moved to the server.
try now at https://arjunphp.com/demo/index.php?/dropzone/index
Amazing! it worked! What did you change? never thought this comments would work hah. Thanks man
Ok more question, how do i use dropzone with other form inputs, e.g a user registration form to take in the name,email and such? Should i put the dropzone form inside another form?or is there a way to change the CSS?
Change the css
did that thank you. how do i now insert the files uploaded to a db with each image being entered in its own row?
I have tried but problem is $fileName returns NULL the whole $_FILES post array is empty but the file is being moved to server. thus i cant grab $fileName and save to db
Sorted! Thanks for the support man
How did you save to the database? I can’t figure it out….
hi want to add this to my own form which includes other fields to. All fields are arranged in table format. How can i put this plugin in my specific td of table. I tried giving . Because i thought that this plugin in there from the class(.dropzone). Please support me. thank u
Place this in b/w , we are sending ajax request to server
thank you for the reply. And sorry for my late reply. My form is submitted through ajax so i cannot add class to form. What can i do in this case.
Hey Arjun
I have the same problem as nicholas mwenda, and it seems you corrected something and made it work in the demo you link to. What did you do in order to make it work? Everything seems to work, but no files are moved to the upload folder. No error messages are shown. Thank you.
Hello…great post. I would like to know if there is a way to delete the files. I already setup the addRemoveLinks to true. It just removing the thumbnails but not the files from server.
removedfile method is Called whenever a file is removed from the list. so use this, like as shown below , and send ajax request to the server and delete the file on the server
addRemoveLinks: true,
removedfile: function(file) {
var name = file.name;
$.ajax({
type: ‘POST’,
url: ”.
data: “id=”+name,
dataType: ‘html’
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
To delete files from the server : http://arjunphp.com/unlink-file-in-codeigniter/
I changed the url to url: ‘../uploads’,
I made it as follows
Dropzone.options.myAwesomeDropzone = { uploadMultiple: true,
addRemoveLinks: true,
removedfile: function(file) {
var name = file.name;
$.ajax({
type: ‘POST’,
url: ‘../uploads’,
data: “id=”+name,
dataType: ‘html’,
success:function(data){
console.log(data);
}
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
};
Do I use $name= $this->input->post(‘id’); to get the name of the file to be deleted into the dropzone.php controller?
and how do I trigger the following delete code?
$file = “uploads/” . $name;
if (is_readable($file) && unlink($file)) {
echo “The file has been deleted”;
} else {
echo “The file was not found or not readable and could not be deleted”;
}
– See more at: http://arjunphp.com/unlink-file-in-codeigniter/#sthash.JCJp1yIe.dpuf
fixed this too, I just had to change th url to url: ‘dropzone/delete’,
and created a delete function in the dropzone controller with the delete code in it.
Hi arjun, thanx for ua help.
I found a way to create thumbnails. May be it will help someone.
public function uploadImage() {
if (!empty($_FILES)) {
$config[‘upload_path’] = ‘./assets/img/photos/’;
$config[‘allowed_types’] = ‘gif|jpg|png’;
$config[‘encrypt_name’] = TRUE;
$config[‘overwrite’] = FALSE;
$config[‘max_size’] = ‘500000’;
$this->upload->initialize($config);
if ($this->upload->do_upload(‘file’)) {
$fileData = $this->upload->data();
$thumbnail = $fileData[‘raw_name’] . ‘_thumb’ . $fileData[‘file_ext’];
$full_path = $fileData[‘full_path’];
$profile = $fileData[‘file_name’];
$new_path = ‘./assets/img/photos/thumb’;
$this->common_model->image_resize($new_path, $full_path, ‘_thumb’, 488, 388, ‘height’);
}
}
}
Hmm how can i resize images based on your script ? thanks
i guess $this->common_model->image_resize($new_path, $full_path, ‘_thumb’, 488, 388, ‘height’); you have to change 488,388 to ur desired size
Hi if you are online please guid eme ya ?
how to use dropzone class image with different fields like name .
please give me soution. how used?
multiple file upload is not working I tried adding uploadMultiple: true,the ui shows uploaded but the files are not added to the server. As per the code above I understand that there is no array looped to get more than one file. Please tell me how I can modify the code above to upload multiple files to the uploads folder. Right now after I set uploadMultiple: true it doesnt even upload one file
are you able to upload single file ? Each file upload is done individually
never mind I finally fixed it got an idea by taking a look at your upload multiple images code
I changed the upload function code to the below and it worked great!
Code for multiple image upload
$count = count($_FILES[‘file’][‘size’]);
foreach($_FILES as $key=>$value)
for($s=0; $sload->database(); // load database
// $this->db->insert(‘file_table’,array(‘file_name’ => $fileName));
}
// $name_array[] = $data[‘file_name’];
}
Is there any way by which we can avoid files with the same name to be uploaded to avoid duplication?
DropzoneJS did not check the dropped file exists or not. so in order avoid duplicate uploads, check server side before moving to target folder.Example :
if( !$file_exists ) //If file does not exists then upload
{
move_uploaded_file( $tempFile, $targetFile );
}
else
{
echo ‘Duplicate file name, please change it!’;
}
thanks for the quick reply and the great website.
Actually the duplicate file doesnt actually get uploaded to the server target folder it just shows on screen.
I want to stop it from being added onscreen and show an error that the file already exists. Maybe I will have to something on the javascript (client side)…
I just love the code igniter tutorials. Just starting with Codeigniter.
I just have one thing Im not able to implement. Below the dropzone I have created another div using the same styling of the dropzone div to show all the files in the uploads target folder, Im just not able to make the image show in the correct aspect ratio (without stretching in the thumnail box) like its been done for the dropzone div.
Hello Arjun,
In the above code U use dropzone class in form tag. I want to use this class some other place. Because I want to insert title, description of that video.
$attributes = array(‘class’ => ‘joinus_form separator upload’, ‘name’ => ‘video_upload_form’, ‘method’ => ‘post’);
echo form_open_multipart(‘brands/upload’,$attributes);
?>
<!—->
Upload New Video
<!–<img src="images/contact.png” alt=””>–>
<!–<img src="images/contact.png” alt=””>–>
<!–<img src="images/contact.png” alt=””>–>
Browse..
<!–
<img src="images/lock.png” alt=””>–>
<input type='hidden' name='thumb_img' value='’ />
Please help me…
So the file is uploaded in the directory i wanted, but it is not saving anything to the database. Does anyone know how to do that ?
How to download it ?
How about remove image ?
I want to remove file from my folder and table ? how ??????? please somebody help me
Hi Arjun I have a problem in dropzone .js would help me out. I have multiple dropzone.js in a single page you can find a breif description of the problem in this link http://stackoverflow.com/questions/32652263/multiple-dropzone-js-in-single-page-php
How can i download complete demo zip file
Hi how can i resize the images using dropzone ?files already insert and upload it
https://github.com/enyo/dropzone/issues/781
I tried but i’m getting a 403 forbidden error. Does anyone have any idea about this?
might be due to .htaccess rewrite rules
Thanks for the tutorial but this will never work. If your form action URL is http://yoursite/index.php/whatever/controller then as soon as the index.php flies away the uploaded file in the temporary folder will dissapear before your controller has a chance to move the file to a permament directory.
Thanks @arjunphp:disqus It’s working fine..
nice
Hey..
Where is getcwd() in this code??