File Upload using dropzone.js and Codeigniter

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.

4 Create a view File Called dropzone_view.php in views.Feed with bellow code

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.

0 0 vote
Article Rating
Subscribe
Notify of
guest
62 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Florian Wartner
6 years ago

Thank you so much! This tutorial will rly help me out with a problem i got on creating a gallery..! 🙂

arjun
6 years ago

you are welcome !

Nagarjuna Immadi
Nagarjuna Immadi
6 years ago

awesome tutorial Arjun. Helps me a lot ………

Manar F. Nassar
Manar F. Nassar
6 years ago

great tutorial ^_^
Thanks a lot ..

arjun
6 years ago

you are welcome ! keep reading

John Paul
John Paul
6 years ago

how to delete a uploaded file or cancel an upload.. can u just show that too

arjun
6 years ago
Reply to  John Paul

sure , next post i will write about it

Guest
Guest
6 years ago

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.

arjun
arjun
6 years ago
Reply to  Guest

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

}

freddy
freddy
5 years ago
Reply to  arjun

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();”;

}

onerinas
6 years ago

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.

arjun
6 years ago
Reply to  onerinas

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.

onerinas
6 years ago
Reply to  arjun

yeah initially id dint work for me ..later i noticed i was linking my view file to minified js file.

arjun
6 years ago
Reply to  onerinas

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

}

onerinas
6 years ago
Reply to  arjun

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

arjun
arjun
6 years ago
Reply to  onerinas

hacking library file is not a good idea

onerinas
6 years ago
Reply to  arjun

in my knowledge(from github wiki-issues), those are changeable values

freddy
freddy
5 years ago
Reply to  onerinas

i follow the insrtuction but nothing helps, how can i prevent another ekstention if users upload wrong ekstention

onerinas
6 years ago
Reply to  arjun

thats not “hacking” they give you option to change. you can read the code comments

nicholas mwenda
6 years ago

ey i can see the visual working but nothing is being moved to the server.

nicholas mwenda
6 years ago
Reply to  arjun

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?

arjun
6 years ago

Change the css

nicholas mwenda
6 years ago
Reply to  arjun

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

nicholas mwenda
6 years ago

Sorted! Thanks for the support man

Александър Александров
Александър Александров
5 years ago

How did you save to the database? I can’t figure it out….

Shrestha Sushil
Shrestha Sushil
6 years ago

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

arjun
6 years ago

Place this in b/w , we are sending ajax request to server

Shrestha Sushil
Shrestha Sushil
6 years ago
Reply to  arjun

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.

Guest
Guest
6 years ago

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.

Alexei Correa Tavares
Alexei Correa Tavares
6 years ago

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.

arjun
6 years ago

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/

james pinto
james pinto
5 years ago
Reply to  arjun

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

james pinto
james pinto
5 years ago
Reply to  james pinto

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.

Jafran
Jafran
6 years ago

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

}

}

}

freddy
freddy
5 years ago
Reply to  Jafran

Hmm how can i resize images based on your script ? thanks

Mudassar Muhammad Khan
Mudassar Muhammad Khan
4 years ago
Reply to  freddy

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

freddy
freddy
5 years ago
Reply to  Jafran

Hi if you are online please guid eme ya ?

husen
husen
2 years ago
Reply to  Jafran

how to use dropzone class image with different fields like name .
please give me soution. how used?

james pinto
james pinto
5 years ago

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

arjun
5 years ago
Reply to  james pinto

are you able to upload single file ? Each file upload is done individually

james pinto
james pinto
5 years ago
Reply to  arjun

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’];

}

james pinto
james pinto
5 years ago

Is there any way by which we can avoid files with the same name to be uploaded to avoid duplication?

arjun
5 years ago
Reply to  james pinto

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!’;
}

james pinto
james pinto
5 years ago
Reply to  arjun

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.

Subrat
Subrat
5 years ago

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…

Александър Александров
Александър Александров
5 years ago

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 ?

Lyheang IBell
Lyheang IBell
5 years ago

How to download it ?

Lyheang IBell
Lyheang IBell
5 years ago

How about remove image ?

Lyheang IBell
Lyheang IBell
5 years ago

I want to remove file from my folder and table ? how ??????? please somebody help me

Demo Version
Demo Version
5 years ago

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

imd_developer
imd_developer
5 years ago

How can i download complete demo zip file

freddy
freddy
5 years ago

Hi how can i resize the images using dropzone ?files already insert and upload it

Ishmeet Singh Malhotra
Ishmeet Singh Malhotra
5 years ago

I tried but i’m getting a 403 forbidden error. Does anyone have any idea about this?

arjun
5 years ago

might be due to .htaccess rewrite rules

Who Knows
Who Knows
4 years ago

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.

Suman Halder
Suman Halder
3 years ago

Thanks @arjunphp:disqus It’s working fine..

Jay Bhagat
Jay Bhagat
3 years ago

nice

Arati Gondaliya
Arati Gondaliya
2 years ago

Hey..
Where is getcwd() in this code??

DMCA.com Protection Status
62
0
Would love your thoughts, please comment.x
()
x