Tutorial: How to Implement Uploadify into an Application

Published October 15, 2009 53 Comments 0 Delicious Bookmarks

How to Implement Uploadify into an Application

Last week I showed how to implement Jcrop into an application. In this tutorial – which also pulls from my experiences developing GetSimple – I implement the jQuery plugin Uploadify.

In this tutorial, we create a simple file upload script that also displays an unordered list of the files in the upload directory. The list of files refreshes via an ajax call every time Uploadify processes a queue.

Demo

View the demo or download the files

The Basic HTML

<h2>Uploadify Application Demo <span id="loader"><img src="img/loading.gif" alt="Loading..." /></span></h2>
<div id="sidebar">
	<!-- form to be replaced by uploadify -->
	<form id="mainftp" action="upload.php" method="post" enctype="multipart/form-data">
		<p><input type="file" name="file" id="file" /></p>
		<p><input type="submit" name="submit" value="Upload" /></p>
	</form>
</div>

<!-- whole div to be refreshed once uploadify is finished -->
<div id="allfiles" >
	<?php
		//list all files via function file included up top
		$handle = @opendir($src_folder) or die("Unable to open $src_folder");
		ListDir($handle,$src_folder);
	?>
</div>

The PHP

//folder where the files are stored at
//you may need to chmod this folder to 775 or 777 for it to work
$src_folder = 'files/';

//file that includes the function to list all files in ul
include("inc/file_list.php");

//if javascript is disabled, the ftp will still work
if (isset($_FILES["file"])) {
	if ($_FILES["file"]["error"] > 0) {
	  $error = 'Error Uploading!';
	} else {
    $count = '1';
    $file_loc = $path . $_FILES["file"]["name"];
    $base = $_FILES["file"]["name"];
    while ( file_exists($file_loc) ) {
		$file_loc = $path . $count.'-'. $_FILES["file"]["name"];
		$base = $count.'-'. $_FILES["file"]["name"];
		$count++;
	}
    move_uploaded_file($_FILES["file"]["tmp_name"], $file_loc);
	}
}

The jQuery

$('#mainftp').uploadify({
	'uploader' : 'js/uploadify/uploadify.swf',
	'script' : 'js/uploadify/uploadify.php',
	'multi' : true,
	'auto' : true,
	'height' : '32',
	'width' : '250',
	'buttonImg' : 'img/browse.png',
	'cancelImg' : 'img/cancel.png',
	'folder' : 'files/',
	onProgress: function() {
		$('#loader').show();
	},
	onAllComplete: function() {
		$('#loader').hide();
		$('#allfiles').load(location.href+" #allfiles>*","");
	}
});

Notes about this javascript:

  • Uploadify was unzipped directly from the download on their site. To upgrade, simply replace the js/uploadify/ folder with the newer version.
  • height and width are for the respective dimentions of your custom button image – the demo’s being in img/browse.png
  • folder is the location where the files will be uploaded to. This is also the folder that should be listed on line #3 of the PHP code above in the $src_folder variable.
  • $(‘#loader’).show(); and $(‘#loader’).hide(); start and stop the loading gif that many applications use now to show that something is being uploaded/processed.
  • $(‘#allfiles’).load(location.href+” #allfiles>*”,”"); – replaces the whole div with the id of allfiles with and updated listing with the newly uploaded files in it

This entry was posted under jQuery, Tutorials and has an RSS feed
53 Comments | Save to Del.ico.us |  

53 Comments

  1. October 19th, 2009 @ 10:40 am

    simen said:

    Ey! How do I increase the accepted filesize?

  2. October 19th, 2009 @ 12:48 pm

    @simen – There are two filesizes you need to worry about. The first is limit within Uploadify. This can be set with adding the variable 'sizeLimit' : '51200', to the script… say right below the ‘folder’ option.

    The second is the PHP installation limit. Sometimes you can’t control this, but you can get that value with the command <?php echo ini_get('upload_max_filesize'); ?>. You can also try and set it inside your PHP script like this: <?php ini_set('max_upload_filesize', 8388608); ?> – 8MB

  3. October 29th, 2009 @ 12:38 pm

    Kris said:

    Hi

    How do you get an error to show in the form? i.e. if the filesize is too big or the file extension is not permitted?

    Many Thanks
    Kris

  4. November 8th, 2009 @ 11:45 pm

    Wan said:

    Hi,

    How do i connect it to mysql? Can’t seems to get this right.

  5. Jeroen said:

    I am having problems when adding your jQuery code. It gives me the following error:
    $(“#mainftp”) is null.
    anonymous()
    anonymous()
    anonymous([function(), function(), function()], function(), Object name=F)
    anonymous()
    anonymous()

    Could you help me?

  6. December 7th, 2009 @ 10:12 am

    @Jeroen – Do you have the HTML part of this tutorial setup the same? I ask because jQuery can’t find #mainftp, and that is the ID i place on the <form> element inside the “HTML” step.

  7. December 9th, 2009 @ 3:37 am

    chzigkol said:

    Is the form tag necessary to get this done?

    I only have a div tag where the input file tag is included and I add in my javascript file the above jquery code.

    When I load the page my input file tag disappears!

    What’s going on?

    In general, I want to upload a file to my server without refreshing the page. Does the uploadify supports that?

    thanks

  8. December 9th, 2009 @ 5:39 am

    George said:

    How can i get the name of the file that was upload from your script?
    Many thanks
    George

  9. December 9th, 2009 @ 7:28 am

    @chzigkol – i consider the form tag necessary if the user doesn’t have javascript enabled. I think it’s just good practice, but you are right – a simple div would work too.

    What is an “input file tag”? I’m a little confused… and yes, the example demo doesn’t do a page refresh, but still updates the file list.

  10. December 9th, 2009 @ 7:29 am

    @George – do you mean to use in a PHP fnction? the filename is $file_loc, in JS, i would have to play around and see, i’m not sure off hand

  11. December 9th, 2009 @ 7:42 am

    George said:

    basically i would like to have another form in the page that will save the name of the file that was uploaded, along with some other fields(for example ‘Image Title’) in the database. is that possible?
    Thanks

  12. December 9th, 2009 @ 12:13 pm

    chzigkol said:

    @chris cagle

    this is the input file

    Upload File

    this is my js code

    $('#pictureuri').uploadify({
        'uploader' : 'path to uploadify.swf',
        'script' : 'path to uploadify.php',
        'cancelImg' : 'img/cancel.png',
        'folder' : 'path to my folder',
    });
    

    The uploadify browse button is appeared, the file that is selected is also appeared on my screen underneath the browse button. When I click on the Upload File link the progress bar comes alive. But when the upload is finished the file isn’t actually uploaded on my server.

    I can’t find out where I do wrong.

  13. December 9th, 2009 @ 12:17 pm

    chzigkol said:

    In my last comment the input type=’file’ is missing. Well it is nothing special. It is a regular one with id=pictureuri

  14. so it’s not a jquery problem – you get the uploadify button. My guess is file permissions. At the top of the PHP code is $src_folder = 'files/';

    Does that folder exist on your server?

  15. statquo said:

    Hi.

    Can You tell me what I have to do to show the upload button?
    Everything works fine but if I change ‘auto’: false, and try to upload the files manually i can’t because upload buttom doesn’t appear.

    I’m using Your demo files.

    And thanks for tut. It’s great.

    statquo

  16. statquo said:

    Problem looks like this

    http://img32.imageshack.us/img32/8576/problemmc.jpg

    How can I add there a upload button?

    Thanks for help ;)

  17. statquo said:

    OK, I think I solved the problem for now :P

    I add

    <a href="$('#mainftp').uploadifyUpload();" rel="nofollow">Upload Files</a>

    after the form and it works fine on the localhost. We’ll see after online :)

    Thanks for the tut. It helps a lot a noobs like me :)

    statquo

  18. statquo said:

    Hello again :)

    Well online it doesn’t work ;(
    After upload it’s saying HTTP error.
    I haven’t found any solution for this so it’s the end of the road for me I and have to use something else.

    Did You have that problem and solved it?

    Thanks
    statquo

  19. January 17th, 2010 @ 7:04 pm

    Brahm said:

    The list does update once Uploadify processes a queue as this tutorial says it should.

  20. January 18th, 2010 @ 4:53 am

    snow said:

    http://www.cagintranet.com/code/uploadify-app/upload.php
    heloo>>>>> any try to use it on IE
    it dosen’t work
    help us to solve this on IE

  21. January 18th, 2010 @ 4:06 pm

    @snow: I will try and look at it… but honestly, I dont use IE

    @Brahm: I just tested it and it is working on my demo again. The problem was that there were too many files to refresh properly… Ive since instituted a cleanup function after the list exceeds 5 files. Thanks for pointing this out.

  22. January 26th, 2010 @ 6:22 pm

    Eduardo said:

    hey, i’ve looked for this over the uploadify documentation, but can’t find how to do it.
    how do i hide the browse button, i.e. the flash object? is there a way to do that?

    besides, i’d like to know if i can call the browse dialog from javascript, sort of a $(‘mainftp’).browse() call… hope you can help me and thanks in advance

  23. February 6th, 2010 @ 10:51 am

    sander said:

    I love it!
    but it would be perfect if it worked in IE..

  24. February 11th, 2010 @ 12:01 pm

    matpicsi said:

    Hy,
    I’ve a question.
    I’ve a page called upload.asp that allow me to do the upload of the files, writing down the files on a db., and other things.
    This page run thanks an other page (xxx.asp)that I post down:
    Code

    Here I’wuold use jquery.uploadify. Now:I’m not able to add at your cod this part: ENCTYPE=”multipart/form-data”.
    Is it possible? How can I configure it?

    thanks

  25. February 11th, 2010 @ 12:02 pm

    matpicsi said:

    Code;
    FORM METHOD=”POST” ENCTYPE=”multipart/form-data” ACTION=”upload.asp”
    INPUT TYPE=FILE NAME=”uploadify”
    INPUT TYPE=SUBMIT VALUE=”Upload!”
    /FORM

  26. February 12th, 2010 @ 11:22 am

    steve said:

    Hi,

    Has a solution been found to display the browse button in Internet Exlporer?

  27. John said:

    Can you please make this to work in IE?
    Would be really helpfull!

  28. March 19th, 2010 @ 9:20 am

    Lars said:

    Why i get a file size error every time?

  29. April 5th, 2010 @ 2:06 am

    i have a file size error too every time.
    is there any new version?

  30. May 6th, 2010 @ 2:10 am

    umar said:

    Hi
    This for this post. I want to add file labels with each file upload but I am not getting how I can get the file labels in uploadify.php I have used the scriptdata paarameter but could not get how to use it further

    also I am not getting where is startFileUpload function defined

    please help me :)

    Umar

  31. May 8th, 2010 @ 7:13 am

    Jeyush said:

    Hi,
    Will the implementation of uploadify being done @ the time of submit the form?

  32. May 20th, 2010 @ 10:19 am

    steve said:

    rubbish…lol..
    dont work on IE?
    Preposterous!

    This ridiculous vanity, when IE (and it’s variants) represent 75% of the browser market!

    (Your own logs dont count, everyone knows geeks use FF and a little Safari!

  33. July 28th, 2010 @ 4:42 pm

    kris said:

    This is nice BUT all the file-infos of uploaded files get lost, after the user makes a page-reload after uploading. how do you prevent this?

    regards
    kris

  34. August 1st, 2010 @ 1:38 pm

    xlad said:

    Hi,

    Please help me, everything seems to be OK, I select image files, the progress bar appears but after is finished disappears , no picture is uploaded, no error.

    Please help!
    I read all docs, make all config, tried on localhost & server same problem.

  35. August 5th, 2010 @ 7:38 pm

    Dan said:

    Im also experiencing the same issues as kris and xlad. It doesnt seem to upload anything. :(

  36. August 24th, 2010 @ 8:55 am

    hello,
    thanks for this wonderful source, i try to attach a button to each file in the file list to get the possibility of delete from server. i have found something to do with a php script but the problem is that the page refrech for each file i delete. Do you think their is a way to do the same think without refreshing the page. Thanks for all
    JS

    ps: this i my code, i only apply changes in file_list.php

    <?php
    /**
    * ListDir PHP function
    *
    */

    function ListDir($dir_handle,$path) {
    global $listing;
    echo "”;
    while (false !== ($file = readdir($dir_handle))) {
    $dir =$path . $file;
    if(is_dir($dir) && $file != ‘.’ && $file !=’..’ ) {
    $handle = @opendir($dir) or die(“Unable to open file $file”);
    echo “”.$dir;
    ListDir($handle, $dir);
    echo “”;
    } elseif($file != ‘.’ && $file !=’..’ && $file !=’.htaccess’) {
    echo ‘‘.$file.’‘;
    echo ”

    “;

    }
    }
    echo “”;
    closedir($dir_handle);
    }

  37. August 24th, 2010 @ 9:05 am

    at the begin of page =

  38. August 30th, 2010 @ 1:14 pm

    hades said:

    I have a “File Size Error” for 100 KB file.
    The same problem it’s also in DEMO.
    How solve this?

  39. August 30th, 2010 @ 1:21 pm

    hades said:

    OK it’s solved by add to jquery.application.js
    -> ‘sizeLimit’: ’2000000′, <- in attributes

  40. Michael said:

    Has anyone figured out how to add to the queue when the button is hidden (hideButton=true)? If so, please share!!!

  41. November 5th, 2010 @ 5:54 am

    Rene said:

    Hi,

    Was implementing your tutorial into website, testing locally with XAMPP. After having several errors with the filesize I’ve checked your code …

    ‘sizeLimit’ : ’51200′, //remove this to set no limit on upload size

    ‘height’ : ’32′, //height of your browse button file
    ‘width’ : ’250′, //width of your browse button file
    ‘simUploadLimit’ : ’3′, //remove this to set no limit on simultaneous uploads

    Then I checked out online Uploadify documentation. Shouldn’t sizeLimit be an integer? Same for height, width, simUploadLimit? For now it looks like the (Apache/PHP.ini) default settings are taken.

    Regards, René

  42. Michael said:

    Regarding the screenshot you have in the top of the artice, do you use tables to align the size and date? Just wondering since it wasn’t in the example :)

  43. January 16th, 2011 @ 10:40 am

    @Michael – Yes, they are displayed in a table… download GetSimple and check out the code on /admin/upload.php

    @rene – you’re probably right… not sure why it’s working on my demo with the quotes..

    @hades – inside the javascript, remove or tweak this: ‘sizeLimit

  44. February 1st, 2011 @ 1:54 am

    Binu said:

    Hi,
    I need one small help,the image is uploaded in the particular folder after i selected the images,but i want to store name of the image and id in database,that is not working…could you please help me

    here is my code:

    $(function() {
    $(‘#custom_file_upload’).uploadify({
    ‘uploader’ : ‘http://mlpredesign.local/photogallery/uploadify.swf',
    ‘script’ : ‘http://mlpredesign.local/photogallery/uploadify.php',
    ‘cancelImg’ : ‘http://mlpredesign.local/photogallery/cancel.png',
    ‘folder’ : ‘/photogallery/uploads’,
    ‘multi’ : true,
    ‘auto’ : true,
    ‘method’ : ‘post’,
    ‘fileExt’ : ‘*.jpg;*.gif;*.png’,
    ‘fileDesc’ : ‘Image Files (.JPG, .GIF, .PNG)’,
    ‘queueID’ : ‘custom-queue’,
    ‘queueSizeLimit’ : 10,
    ‘simUploadLimit’ : 10,
    ‘removeCompleted’: false,
    ‘hideButton’ : false,
    ‘onSelectOnce’ : function(event,data) {
    $(‘#status-message’).text(data.filesSelected + ‘ files have been added to the queue.’);
    },
    ‘onAllComplete’ : function(event,data) {
    $(‘#status-message’).text(data.filesUploaded + ‘ files uploaded, ‘ + data.errors + ‘ errors.’);
    },
    ‘onComplete’ : function(event,queueID,fileObj,response,data) {
    $(‘#hiddenFormField’).val(response);
    },
    ‘onAllComplete’ : function(event,data) {
    $(‘#frmphotogallery’).submit();
    // },
    });
    });

  45. waqas said:

    Thanks for a great tutorial.
    I am having a problem in deleting an uploaded file, with the script provided above.
    Please help me.

  46. March 9th, 2011 @ 12:02 pm

    efoenix said:

    thank you, i’have download source, but it doesn’t work, please help me

  47. April 21st, 2011 @ 5:29 am

    Pavan said:

    Can any one provide me with a working example of Uplodify and Servlet

    Thanks in advance

  48. June 16th, 2011 @ 6:19 am

    It seems no matter where I change the “sizeLimit” either in my javescript on the upload page or in the “jquery.uploadify.v2.1.0.min.js” file it still won’t upload any of my images, my files are about 1.6MB.

    My server is allowing 64MB file uploads so it’s not that.

    Any ideas???

  49. June 16th, 2011 @ 6:24 am

    My bad, mis-read hades post. I fixed by removing the “sizeLimit” in “jquery.application.js” file as suggested by Chris.

    Cheers

  50. July 6th, 2011 @ 1:07 am

    gwc said:

    Here is eg for every. That can save image file name and other information together in the database how-to-add-image-name-and-other-information-together-in-uploadify. I think you will get it.

  51. July 8th, 2011 @ 6:41 am

    Dan said:

    I’ve just fixed my issue,

    For anyone having the same issues as me and xlad above, do this.

    In a virtual hosting environment (usually linux based) the DOCUMENT_ROOT in the document was returning the virtual path,

    Where you actually need the full DIR path to the $targetPath.

    To fix the issue of the file not showing you need to insert this code into js/uploadify/uploadify.php – Line 26

    $_SERVER['DOCUMENT_ROOT'] = str_ireplace($_SERVER['SCRIPT_NAME'], ”, $_SERVER['SCRIPT_FILENAME']);

    Once you’ve added that and you’ve CHMOD’d the files folder to 755 or 777, your uploadifty will upload the file and place it into the directory as originally intended.

    Hope that helps someone!

  52. August 1st, 2011 @ 7:17 am

    Bruno Quintanaa said:

    Hello!
    Congratulation for your code! I have a problem, I try to remplace on the file:

    jquery.application.js
    the line:

    'folder' : 'files/', //folder to save uploads to

    And I would like to make something like this:

    $folder_by_get = $_get['from_input'];
    'folder': ;

    Is possible? because I tried but Is not working, maybe I need to put in java, but I don’t know to programming in Java, thank you in advanced!
    :)

  53. August 1st, 2011 @ 7:19 am

    Bruno Quintanaa said:

    Sorry, I forgot to put before! ehehe
    “And I would like to make something like this:

    'folder': $folder_by_get;

Leave your Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get your own Gravatar