The base behind HTML5 drag and drop
is h5ml5s newly added HTML5 FILE API. Before this it was impossible to read file contents locally using javascript but now it’s possible to read files locally using File reader object which lets read file contents as raw data buffer, which we can send to server via ajax.
1 2 3 4 5 |
reader = new FileReader(); reader.onload = function(e){ alert(e.target.result); } reader.readAsDataURL(file); |
HTML5 drag and drop file upload progress bar
In this demo we have created drag and drop feature which is based on File DataTransfer object. DataTransfer object holds information about the user interaction, including what files (if any) the user dropped on the element to which the event is bound.
1 2 3 4 5 6 7 8 9 10 11 |
function drop(e) { $(this).removeClass("active"); defaults(e); // dataTransfer = which holds information about the user interaction, including what files (if any) the user dropped on the element to which the event is bound. //console.log(e); var dt = e.dataTransfer; var files = dt.files; handleFiles(files,e); } |
File upload progress event
There is one more thing that needs to be discussed, Upload Progress. Once we open (start) XMLHttpRequest() we need to attach progress event to upload process so that we can show numeric stat’s to the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
xhr = new XMLHttpRequest(); xhr.open("post", "ajax_fileupload.php", true); xhr.upload.addEventListener("progress", function (event) { console.log(event); if (event.lengthComputable) { $("#progress").css("width",(event.loaded / event.total) * 100 + "%"); $(".percents").html(" "+((event.loaded / event.total) * 100).toFixed() + "%"); $(".up-done").html((parseInt(event.loaded / 1024)).toFixed(0)); } else { alert("Failed to compute file upload length"); } }, false); |
Dont forget to change “uploads” directory permissions.
Liked this “HTML5 drag and drop file upload progress bar” then don’t forget to share HTML5 drag and drop file upload progress bar
This does not work on IE9 Perhaps you should make a mention of it on your post. Just a suggestion.
Miguel
yes it doesnt work in IE, IE still doesnt support all the html5 features properly.
hi amlt! can you tell me if i can change it so it can upload other then just image! ? please
thanks for sharing…
sorry for re-post …
and how if you could provide or point out where the code needed to be changed i would be greatfull
thanks again !
anon
Yes you need to make changes to script.js file. find the line ” var imageType = /image.*/;” and add more file types or just remove the if condition and it will allow all type of files to be uploaded. Just dont forget to block EXE files, otherwise u will be screwed.
hi friend i wonder if i can use this script and modify it to work in my web site if u agree
thnxs alot
nice work i hope u more scucess
^_*
Yes you can use it.
thanks alot ! hehe
1 more thing if you dont mind
disallow extensions like htacc htpass php and other scripts from people uploading
and if you really feeling like helping me can you point me or give me example on how to display uploaded file
(i seen 1 guy used uber uploader to upload the file and used some free source displayer to display the file)
please feel free to help me out if can in anyway my brain almost dead 🙂 and thanks for your kind reply!
to be honest i didnt think you would reply in first place 🙂 thanks in advance
Yes you are right we need to disallow extensions like htacc htpass php and other scripts, so that i am only allowing files with jpg extention, to be more cautious i am renaming file to .jpg at server side so even if user uploads any other file than .jpg finally it will get renamed to jpg. If you have firebug installed you can see server script returns file name. All the files are getting uploaded to directory named “uploads” so u can access file @ base url/uploads/returned file name.
And really sorry for the late reply, i was away from internet for some reasons.
Hey, thanks for this awesome tutorial!
I have a little problem though, when I try to upload files I get the error ‘ErrorInternal Server Error’ when the upload reaches 100%. And the file doesn’t seem to be uploaded to ‘uploads’. Anything i need to change to solve this?
Thanks,
Steven
Are you using linux ? Check your directory permission. Directory should have write permission.
Thanks for the quick reply,
The directory permission of ‘upload’ is on 777.
I tried it on a different server( differrent hosting company) and it works!
So i’ve send an email to the hosting company because maybe it’s something only they can change.
I know very little to nothing about servers/networks myself sadly.
Glad to know its working now 🙂
Works aswell on other server now, had to add an .htaccess file to disable the Mod_Security 🙂
@steven : Thanks for posting the solution, This might help other visitors.
There is no way to upload multiple files at once?
Hugs.
Right now this script doesnt support multiple file uploads at one, you may expect its newer version.
[…] css3 and html5 like creating css3 flowers using gradient effect, Introduction to HTML5 web storage, Ajax file upload with drag and drop and progress bar. In this tutorial we will look at the new css3 feature CSS3 transition. […]
Ahh! Thanks for this post. This removed my headache, I’ve been searching for a post like this for 2 days now, this is the only on that works. I am new to html5 and javascript/ajax, I think that’s the reason why I am not able to use the earlier posts that I encountered. Thank you again. Btw, I was able to do the multiple upload by putting a while loop inside the handle files. xD Thanks again sir!
Hi,
Very nice tutorials, really thanks to you.
Buddy i am ruby on rails dev, my question is – when u r sending ajax request to server (ajax_fileupload.php )
Then what are you returning , you have written 3 lines
So from code as i am understaning:
1. You are reading file contents
2. You are generating filename
3. You are wrting contents to the file.
Then what are you returning to the client, and which line is performing that return
I have never worked on php, so please if you can answer me.
Thanks in advance
Prashant
Your understanding it right. 3 lines are sufficient. Actually php’s role in this script is almost nothing, Its all handled by HTML5 and javascript.
If you take a look at the javascript you can notice i have bind “progress” event which returns number of bytes transferred, that it.
xhr.upload.addEventListener("progress", function (event) {
console.log(event);
if (event.lengthComputable) {
$("#progress").css("width",(event.loaded / event.total) * 100 + "%");
$(".percents").html(" "+((event.loaded / event.total) * 100).toFixed() + "%");
$(".up-done").html((parseInt(event.loaded / 1024)).toFixed(0));
}
else {
alert("Failed to compute file upload length");
}
}, false);
Hey
I’m new to this.
I’m not able to run the code properly. I’m getting an alert box saying “Error” when I upload a picture. I want to remove the php part. Can you please suggest me something in jquery or javascript for the PHP part used by you.
Thanks in advance
Try to clear your cache, then make sure you are using latest browsers which support HTML5, like latest chrome or firefox. That error comes up when xhr.status != 200v (Status code:200 means, everythings ok)
Is it possible to create a dropbox which will take the image dropped on it but the file will be submitted only when user clicks submit along with other fields in the form?. I don’t want to upload the image through ajax.
Then i guess you need to use iframe technique or may be traditional upload method
[…] a previous post i demonstrated how to make Ajax file upload HTML5 drag and drop file upload progress bar which is fine if you are uploading single file, but i found that users are more interested in […]
it is not working ie-9 … is there any solution for it ?
Yes its doesnt work in IE, There is no way to make it work because it is purely implemented using HTML5 which is not supported yet in IE 9.
this demo is helped me,thanks!
it works well in chrome,but there are two problems in Mozilla.
it doesn’t trigger the progress event,when i upload files less then 100k.
some times,the progress stops after it reaches 99%, if i want to show ‘processing file’ after upload successfully and before the request end ,how can I deal with it?
It might be because, you chrome version is latest and supports file api properly, Check if your firefox has latest update. Even for small images it does triggers the event shows the progress bar but you dont notice it because image size is too small and it happens within fraction of second, i just tested it with 16kb image and i see progress bar (i am using Firefox version 22). for “processing file” message you can put “if” condition and check if progress == 99 then status = “processing file”.
I don’t have Facebook. How can I get the file?
Check your gmail, i have just sent you the script.
Hey bro how can i upload multiple images at once.what are the lines i have to change
This is what exactly it does ? what are you looking for ?
First of all, Thanks for the code. Please let me know how to change page location after completing the file upload. I mean if the image upload is successful I need to do the rest on another page , but how can I navigate from this page to another only after image is being uploaded to the server.
You need to add one line in script.js file. Just find
$(".percents").html("100%");
and below that addwindow.location
there.Can you please help me to solve this? I tried like u said, but it is not working properly … Actually my requirement is if the image upload is successful I have to do database operation that I can do with ‘ajax_fileupload.php’ ( I think so, right ? ) , and after that I have to relocate to another page with the image id. How can I do this ? can you please help me. ?
In ajax_fileupload.php file set $filename in session variable and then access it on next page.
Hi Amit,
I’m very happy to see your post. I want to get some image information. I want to implement image uploading feature which is showing in this website http://www.ubersnap.com.
Please see the link http://blog.rrikesh.com/jquery/how-to-get-exif-data-from-images-using-jquery/.
Can we migrate this script with your script. if this is possible please give me instruction.
looking for your positive response
Thank’s and regards.
Rajesh verma
Yes you can integrate that with this script, Just add your code in
function drop(e)
function. Also have a look at the advanced version of the same script https://amitpatil.me/drag-and-drop-multiple-file-upload-with-progress-bar/Have you tutorial of file uploading with only progress bar. and form registration with captcha code.. thanks.. post me on my fb id ikhlas313@yahoo.in
Hi..i just downloaded the code and when I executed it in google chrome, I am getting error “Failed to compute file upload length”.
Please let me know where I went wrong. If possible, can you please provide asp.net version of ajax_fileupload.php file, as I am not aware of PHP.
Your support and help will be very much appreciated.
Looking forward for your reply.
Try with different images, it should work. Unfortunately i dont have asp.net code.
Hello
I can’t download your code, every time I get
Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)
Could you please check? Anyway, thanks for your best upload script.
Check now.
Yes, perfect, thanks a lot!
I have used your script for images upload, but any big image crashes Chrome. It is because of this bug:
https://code.google.com/p/v8/issues/detail?id=2534
Any workaround?
Tim, Yes it seems like so because we are using both the things FileReader+XMLHttpRequest.
Hello,
Can you please post the .php code in .aspx , I have requirement in asp.net.
Thanks
Naresh.
There are only few lines of php, i guess 4-5 lines only. There is no need to change the js. Just convert php code to asp.net and it will work.
Hi Amit
Great script. Thanks.
Is there any way to keep the uploaded filename the same?
Thanks.
That script was made to just elaborate how new html5 file reader api works. I would suggest you to have a look at this plugin. http://malsup.com/jquery/form/#file-upload
Amit, it could be a great tool, but you saying I can’t get back the original file-name after uploading?
For better control use form.js plugin
Please send me download file for ajax file upload html5…………
Thanks an advance…..
Very nice post, keep up the nice work. Do you have an RSS Feed? See you
HI amit,i need pure html not with any php code.
All the code should be in html and support can be with jquery and javascript but not with any php file
Did you tried yourself ? If not using php how will you copy file to server ?
Thanks for your awesome script, i noticed one thing in this script that when uploading multiple images it overwrites the previous one in HTML, only shows the last file uploaded. Can you alter it so you can see all the images uploaded? in a list or something?
I’ve tried for a couple of hours but didn’t work for me (i’m not an expert).
I’d added this to line 44
for (var i = 0, f; f = files[i]; i++) {
var file = files[i];
but now i’m stuck how to add multiple uploads visable to a div with a id.
Hope you can help! 🙂
There is updated version of this script, Please try that one, New version supports multiple uploads.
[…] Demo Download […]
[…] Demo | Download […]
Thank you for this plugin
when i need to use 2 or three input files for upload what i must change ?
thanks
There is another blog post for multiple uploads https://amitpatil.me/drag-and-drop-multiple-file-upload-with-progress-bar/