Aug 03

Unfortunatly we only lhave a few ways to upload files without reloading the whole page. You can do this by using an iframe, flash or through a java applet. Since applets support drag and drop, we can use it to create a drag and drop file uploader.

This is the html to hold the java applet. We chuck in a text field so we can pass additional information with the applet’s file post.

    <input id="meta-text" />
    <button onclick="javascript:document.applets.uploadApplet.setMetadata(document.getElementById('meta-text').value);">Set metadata</button>
    <br />
    <applet type="application/x-java-applet" name="uploadApplet" id="uploadApplet" code="dndapplet/applet/DNDApplet" archive="signed_dndapplet.jar" mayscript="true" scriptable="true">
        <param name="uploadPath"                      value="uploader.php">
        <param name="funcNameHandleCurrentUpload"     value="handleCurrentUpload">
    </applet>

When a file is draged and dropped into the applet, it submits the file to the location passed through the uploadPath param. The upload works the same way as any FILE/POST form submit. So we write some PHP to handle it and return how the upload went.

$uploadPath = "./uploads";
$maxfilesize = 30000; //kByte
$tmp_name  = $_FILES['uploadfile']['tmp_name'];
$file_name = $_FILES['uploadfile']['name'];
$tgt_path  = "$uploadPath/$file_name";
$field_name = 'uploadfile';

if ($_FILES['uploadfile']['size'] > $maxfilesize*1024)
   die ("File exceeds maximum filesize: $maxfilesize kByte.");

if ( ! is_writable( $uploadPath) )
	die ("Upload path is not writeable.");

if ( ! move_uploaded_file( $tmp_name, $tgt_path ) )
  die ("Problem during upload.");

echo "$file_name Upload successful. Metadata: " . $_POST['metadata'];

Finally, we have to go back to the html page and write some javascipt to handle the value returned by the applet.

function javascript_callback (return_str)
{	alert(return_str);
}

Now we are all done. You can download the demo and the source code live demo link . If you want to change the appearance of the applet, you can edit the code .

Here’s the live demo link and the full source code

61 Responses to “Cross-browser drag and drop file upload”

  1. Jordan Says:

    You absolutely can do AJAX uploads with Javascript – you don’t need extras like iframes, Java, or Flash. (Not drag-and-drop, of course)

    Two examples:
    http://www.phpletter.com/Our-Projects/AjaxFileUpload/
    http://tomas.epineer.se/archives/3

    Why use iframes, or Java/Flash (which require extra plugins to be installed), when they’re not necessary?

  2. Chris Gunn Says:

    Hi Jordan,

    I think you missed the “drag and drop” part of the title. Also XHR doesn’t support file uploads. (your second link says just this: “Since the XMLHttpRequest object doesn’t support file uploads, this had to be done using iframes. “)

  3. ESL Says:

    Hello, My name is William Foo and I am now in North Carolina. I hope someone has seen any resource that is quite the same as this ESL instructional site. I have no budget whatsoever, appreciate if you let me have the link to any such free resource. Write me.

  4. Fire Basket Says:

    -”" I am really thankful to this topic because it really gives great information “~*

  5. Saberdweller Says:

    [url=http://meetka.com/s.php?f=2519][b]сайт знакомств planet[/b][/url]

    [url=http://erodatings.com/s.php?f=2519][img]http://i20.fastpic.ru/big/2011/0427/c8/2f53e67c0359d89fb5961d27c3a6b9c8.gif[/img][/url]

    Представляем на Ваше внимание [url=http://rudatings.com/s.php?f=2519][b]mamba tv сайт знакомств[/b][/url], на сегодняшний день в мире среди молодежи и не только, огромнейшей популярностью пользуются [url=http://rudatings.com/s.php?f=2519][b]мамба большой сайт знакомств[/b][/url].Обязательно к нам Присоединяйтесь! Будьте уверены, Вас томительно ожидает Ваша вторая половинка! Только на [url=http://erodatings.com/s.php?f=2519][b]сайт знакомств 24open ru[/b][/url] несколько десятков тысяч посетителей каждый день. Большую часть своего времени мы отдаем работе, поэтому просто не остается сил и времени на знакомства в барах, клубах, на улице и т.д., спасает [url=http://rudatings.com/s.php?f=2519][b]где можно познакомится с девушкой[/b][/url].
    С помощью [url=http://meetka.com/s.php?f=2519][b]где можно познакомится с девушкой[/b][/url] посетители могут создавать личные странички, добавлять фотографии, видео, создавать и участвовать в группах. Искать свою половинку с помощью [url=http://erodatings.com/s.php?f=2519][b]свинг клуб знакомства[/b][/url] шести видов поиска стало еще легче!

    Только на [url=http://erodatings.com/s.php?f=2519][b]знакомства на e mamba[/b][/url] Вы сможете:
    - Разнообразить свою сексуальную жизнь
    - Интимные прелести в первый вечер
    - Поиск партнера в короткий срок
    - Полная анонимность ваших данных
    - Несколько тысяч анкет парней и девушек желающих познакомиться

    Знакомства для серьёзных отношений и не только — такова цель многих посетителей [url=http://rudatings.com/s.php?f=2519][b]сайт общения и знакомств[/b][/url], ежедневно регистрирующихся у нас. С помощью [url=http://meetka.com/s.php?f=2519][b]mamba znakomstva ru[/b][/url] вы без особого труда сможете найти себе партнера для секса или отношений. Зарегистрируйтесь сейчас и используйте интимные знакомства.

    Так же на [url=http://rudatings.com/s.php?f=2519][b]lifemeet социальная сеть секс знакомств[/b][/url] возможно:
    - Вести свой личный Блог
    - Создавать свои Фотоальбомы доступные только для ваших знакомых
    - Создавать и учавствовать в опросах и событиях
    - Искать интересующие Вас объявления и добавлять свои
    - Создавать свои группы по интересам
    - И многое, многое другое!

    [url=http://erodatings.com/s.php?f=2519][b]Вход на сайт знакомств !!![/b][/url]

    [url=http://meetka.com/s.php?f=2519][b]хочу познакомиться с красивой девушкой[/b][/url]
    [url=http://erodatings.com/s.php?f=2519][b]www 24open ru знакомство[/b][/url]
    [url=http://erodatings.com/s.php?f=2519][b]клуб знакомств мамба[/b][/url]
    [url=http://meetka.com/s.php?f=2519][b]женщина желает познакомиться[/b][/url]
    [url=http://rudatings.com/s.php?f=2519][b]как познакомиться через интернет[/b][/url]

  6. Denmark Green Card Says:

    I like your post. Good job!

  7. Crossfire Hacks Says:

    I?m now not positive where you’re getting your information, however good topic. I must spend some time finding out more or figuring out more. Thank you for fantastic information I used to be searching for this information for my mission.

  8. BG mail Says:

    Thank you for the sensible critique. Me & my neighbor were just preparing to do some research on this. We got a grab a book from our local library but I think I learned more from this post. I am very glad to see such wonderful info being shared freely out there.

  9. celebrity birthdays Says:

    I definitely wanted to jot down a quick remark to be able to appreciate you for these remarkable guides you are giving at this website. My time consuming internet lookup has now been compensated with professional information to write about with my partners. I ‘d point out that we readers are definitely fortunate to live in a useful network with so many brilliant professionals with valuable solutions. I feel very fortunate to have seen the web site and look forward to tons of more fabulous minutes reading here. Thanks once again for everything.

  10. yeah Says:

    It is truly a great and helpful piece of information. I am happy that you just shared this useful info with us. Please stay us informed like this. Thanks for sharing.

  11. Car Hire Comparison Says:

    Thanks, I have recently been searching for info about this topic for a while and yours is the best I’ve came upon so far. But, what in regards to the bottom line? Are you positive concerning the supply?

  12. Dino Rothery Says:

    Aw, this was a very nice post. In idea I would like to put in writing like this moreover – taking time and precise effort to make an excellent article… but what can I say… I procrastinate alot and on no account appear to get one thing done.

  13. justin bieber party favours Says:

    hello people!! Brilliant site!

  14. grammar check online Says:

    Delzer780@yahoo.com

  15. Find Work Says:

    Great – I should definitely pronounce, impressed with your website. I had no trouble navigating through all the tabs and related info ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, website theme . a tones way for your client to communicate. Excellent task.

  16. Music Instrument Says:

    I haven’t checked in here for a while since I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my daily bloglist. You deserve it my friend :)

  17. Free Classified Ads USA Says:

    My brother recommended I might like this blog. He used to be entirely right. This submit truly made my day. You cann’t consider just how much time I had spent for this info! Thank you!

  18. West Ham Says:

    Excellent blog right here! Additionally your web site lots up very fast! What host are you using? Can I get your affiliate hyperlink on your host? I wish my website loaded up as quickly as yours lol.

  19. Virtual Private Servers Says:

    I am usually to blogging and i really recognize your content. The article has really peaks my interest. I am going to bookmark your site and maintain checking for brand spanking new information.

  20. pianoforte Says:

    I was recommended this blog by way of my cousin. I am not sure whether this put up is written by way of him as no one else know such particular approximately my problem. You’re wonderful! Thanks!

  21. mmn Says:

    Usually I don’t learn post on blogs, however I would like to say that this write-up very pressured me to try and do it! Your writing taste has been amazed me. Thanks, very nice article.

  22. photographer Says:

    Good day very cool web site!! Guy .. Excellent .. Amazing .. I will bookmark your blog and take the feeds additionally…I am satisfied to search out a lot of helpful information right here in the submit, we want work out more strategies in this regard, thanks for sharing.

  23. Melvin Taberski Says:

    Only wanna input on few general things, The website style is perfect, the articles is rattling superb. “We can only learn to love by loving.” by Iris Murdoch.

  24. One Owner Lease Return Says:

    My brother suggested I may like this blog. He was totally right. This post actually made my day. You cann’t imagine simply how so much time I had spent for this info! Thank you!

  25. sell cell phones for cash Says:

    Great paintings! That is the type of information that should be shared around the web. Shame on Google for now not positioning this publish upper! Come on over and seek advice from my web site . Thanks =)

  26. software Says:

    I like what you guys are up too. Such smart work and reporting! Keep up the excellent works guys I’ve incorporated you guys to my blogroll. I think it will improve the value of my site :) .

  27. arcopedico Says:

    Hello there, I found your site via Google at the same time as looking for a related topic, your website got here up, it seems good. I’ve bookmarked it in my google bookmarks.

  28. showers Says:

    I’m usually to running a blog and i actually respect your content. The article has really peaks my interest. I am going to bookmark your web site and keep checking for brand new information.

  29. bestsellers Says:

    I do trust all the concepts you have presented in your post. They’re very convincing and can definitely work. Nonetheless, the posts are too brief for starters. Could you please prolong them a little from next time? Thanks for the post.

  30. men uggs sale Says:

    strongzz I’ve read several good stuff here. Certainly worth bookmarking for revisiting. I wonder how much effort you put to make such a excellent informative web site.

  31. Buy Lelo Sex Toys Says:

    I want to point out my passion for your kindness in support of visitors who must have assistance with in this topic. Your special commitment to passing the message up and down appears to be astonishingly helpful and has surely permitted associates just like me to arrive at their goals. The warm and friendly help and advice indicates so much a person like me and a whole lot more to my colleagues. Warm regards; from each one of us.

  32. wimax Says:

    Over again eager article thanks loads for sharing, keep me posted I’ll be reading more of your posts in the future day!

  33. kim ekman Says:

    This website online is mostly a stroll-by means of for all the information you needed about this and didn’t know who to ask. Glimpse here, and you’ll undoubtedly discover it.

  34. Google Says:

    I want to get across my admiration for your kind-heartedness supporting all those that actually need guidance on this one concern. Your personal commitment to passing the solution up and down appeared to be astonishingly invaluable and has constantly allowed those like me to reach their dreams. The insightful help and advice can mean a whole lot a person like me and extremely more to my peers. Best wishes; from each one of us.

  35. Лучший фотограф в Израиле Says:

    You can definitely see your enthusiasm in the paintings you write. The arena hopes for even more passionate writers such as you who are not afraid to say how they believe. Always follow your heart.

  36. uggs cheap Says:

    Somebody necessarily lend a hand to make severely posts I would state. That is the first time I frequented your website page and to this point? I surprised with the research you made to make this actual post amazing. Wonderful job!

  37. best business voip providers Says:

    I would like to thank you for the efforts you’ve put in writing this website. I’m hoping the same high-grade web site post from you in the future also. In fact your creative writing abilities has inspired me to get my own website going now. Really blogging is spreading its wings and growing fast. Your write up is a great example.

  38. stiforp Says:

    Pretty nice post. I simply stumbled upon your weblog and wished to say that I’ve really loved surfing around your weblog posts. In any case I’ll be subscribing on your rss feed and I am hoping you write again soon!

  39. знакомства Says:

    Simply want to say your article is as astonishing. The clarity to your put up is just great and i can think you’re an expert in this subject. Fine along with your permission let me to clutch your RSS feed to keep updated with coming near near post. Thanks a million and please keep up the rewarding work.

  40. знакомства Says:

    Terrific paintings! That is the kind of info that should be shared around the internet. Disgrace on Google for now not positioning this submit upper! Come on over and talk over with my web site . Thanks =)

  41. знакомства Says:

    Excellent post. I was checking continuously this blog and I am impressed! Extremely useful info specifically the last part :) I deal with such information much. I was seeking this certain info for a long time. Thanks and best of luck.

  42. Argelia Toothman Says:

    I was reading through some of your blog posts on this website and I believe this site is very instructive! Keep on putting up.

  43. Dusti Ditucci Says:

    Very informative and great anatomical structure of subject matter, now that’s user pleasant (:.

  44. Ethan Villalvazo Says:

    After study just a few of the weblog posts in your website now, and I truly like your method of blogging. I bookmarked it to my bookmark web site checklist and will probably be checking back soon. Pls check out my site as effectively and let me know what you think.

  45. drug rehab centers in raleigh nc Says:

    Denver features a treatment that is certainly known as the “rocky huge batch rehabilitation

  46. знакомства для секса Says:

    Great weblog here! Additionally your site lots up fast! What host are you the use of? Can I am getting your associate hyperlink to your host? I desire my website loaded up as fast as yours lol

  47. Leo Mcgaffey Says:

    posts !
    This company ja alcaçou 3rd place among the top 100 leading companies network marketing!

  48. Enola Mcintrye Says:

    Outstanding post, I believe blog owners should larn a lot from this website its really user pleasant. So much superb information on here .

  49. Reid Jupiter Says:

    I don’t really get how this is much of a difference between the San Diego Tribune publishing this or some type of blog. Material like this must to be pushed out more often. I would hope that people in America would stand up for peoples rights like this.

  50. Ashlee Chupp Says:

    This specific truly responded to our dilemma, many thanks!

  51. knit hats Says:

    In my opinion that a foreclosure can have a significant effect on the applicant’s life. Mortgage foreclosures can have a Seven to a decade negative relation to a client’s credit report. The borrower who may have applied for home financing or any loans for that matter, knows that the worse credit rating is actually, the more challenging it is to acquire a decent bank loan. In addition, it could affect the borrower’s ability to find a good place to let or rent, if that results in being the alternative property solution. Interesting blog post.

  52. euro milions Says:

    I must convey my appreciation for your kindness in support of visitors who really want help on the theme. Your real dedication to passing the message all over had become rather powerful and has all the time made guys and women like me to realize their goals. Your amazing warm and helpful suggestions implies this much a person like me and substantially more to my mates. Many thanks; from everyone of us.

  53. password crack software Says:

    What’s up.This particular report came down to unusual, notably as a result of I used to be in the market for the thing it this unique topic area this morning.

  54. Julienne Hainer Says:

    I’ll be honest, I’m kinda confused. But nice blog.

  55. menottes sexe Says:

    It is difficult to get well informed folks with this issue, and you sound like you know what exactly you are talking about! Thanks a lot

  56. Joao Pedro Says:

    http://indiemoines.com/category/spirituality/

  57. Joao Pedro Says:

    http://users2.smartgb.com/g/g.php?a=s&i=g26-08750-92

  58. Columbus Garfinkle Says:

    I am most intrigued by the storyline, though the cover takes a different approach than most UF. Sounds great!

  59. Dustin Says:

    I like the valuable info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite certain I’ll learn lots of new stuff right here! Good luck for the next!

  60. erotic fantasy toys Says:

    Thank you for another informative website. Where else could I get that kind of information written in such an ideal way? I’ve a project that I am just now working on, and I have been on the look out for such information.

  61. chelcie wimmer Says:

    I want to to thank you for this very good read!! I definitely enjoyed every bit of it. I have got you book marked to look at new stuff you post…

Leave a Reply