Site Meter
 
 

jQuery Ajax uploader plugin (with progress bar!)

Do your web applications ever involve letting the user upload a file? If so, how’s the end-user experience: do you show a nice progress bar during the upload, or do you just leave the user waiting for minutes, with no clue when (if ever) the upload will complete?

Please show a progress bar, otherwise users will be justified in hating you. Check out this video to see one way it can work:


If you’re not seeing a video here, your feed reader is hiding it. View this post in a browser to see the video.

Those of you who attended my ASP.NET MVC talk at DDD7 last weekend might recognise this ;)

To create this behaviour, I implemented a simple jQuery plugin that replaces normal <input type=”file”/> elements with funky Ajaxy asynchronous uploader widgets. Behind the scenes, it uses the excellent SWFUpload library. All the clever stuff is in SWFUpload; all I did is set up the progress bar / cancellation behaviours, and make it easier to use if you’re already using jQuery.

Notice that it still works if the user doesn’t have JavaScript running in their browser. It gracefully degrades to “traditional” <input type=”file”/> behaviour. This is known as progressive enhancement or unobtrusive JavaScript.

Download

Here are all the files you need to accomplish this: Download jQuery-asyncUpload-0.1.js.

Setup instructions

Uploading files via Ajax, by nature, involves setting things up both on the server and on the client. The most reliable way to get this working successfully in your own app is to download the demo ASP.NET MVC project (see the end of this post) and copy the relevant aspects of its workings into your own app.

Nonetheless, here is an outline of the steps needed to get jQuery-asyncUpload-0.1.js working in your app, assuming you’ve already got jQuery in there:

1.  Add jQuery-asyncUpload-0.1.js, swfupload.js, and swfupload.swf to your project. In an ASP.NET MVC app, you might like to put these in /Scripts.

2.  Add script tags to reference the JavaScript files.

<head>
    <!-- Adjust the file paths as needed for your project -->
    <script src="/Scripts/jquery-1.2.6.min.js"></script>
    <script src="/Scripts/swfupload.js"></script>
    <script src="/Scripts/jquery-asyncUpload-0.1.js"></script>
</head>

3.  Add an old-style HTML file upload control to one of your pages:

<input type="file" id="yourID" name="yourID" />

4. Add a jQuery statement that replaces this file upload control with an asynchronous uploader when JavaScript is available:

<script>
    $(function() {
        $("#yourID").makeAsyncUploader({
            upload_url: "/Home/AsyncUpload", // Important! This isn't a directory, it's a HANDLER such as an ASP.NET MVC action method, or a PHP file, or a Classic ASP file, or an ASP.NET .ASHX handler. The handler should save the file to disk (or database).
            flash_url: '/Scripts/swfupload.swf',
            button_image_url: '/Scripts/blankButton.png'
        });
    });
</script>

These options are explained later in this blog post. You must make sure to correctly reference the location of swfupload.swf, and put a button image wherever button_image_url specifies.

5. Add some CSS rules to style the progress bar. I’m using the following, though bear in mind it has some nasty hacks to make IE do an inline float properly. CSS gurus might structure this more cleanly.

DIV.ProgressBar { width: 100px; padding: 0; border: 1px solid black; margin-right: 1em; height:.75em; margin-left:1em; display:-moz-inline-stack; display:inline-block; zoom:1; *display:inline; }
DIV.ProgressBar DIV { background-color: Green; font-size: 1pt; height:100%; float:left; }
SPAN.asyncUploader OBJECT { position: relative; top: 5px; left: 10px; }

5. At this point, check you have something working. The visitor should now be able to select a file to upload, and should immediately get an alert box saying “Error 404” – that’s because you’ve configured the control to do an asynchronous upload to /Home/AsyncUpload, but your web app probably doesn’t have anything at that URL.

Also, if you use FireBug to inspect the DOM, you’ll see that your <input type=”file” /> has been dynamically replaced with the following:

<span class="asyncUploader">
   <div class="ProgressBar" style="display: none;">
	<!-- This is the progress bar itself - you can style it with CSS -->
   </div>
   <object type="application/x-shockwave-flash" ... >
       ... SWF config here ...
   </object>
   <input type="hidden" name="yourID_filename"/>
   <input type="hidden" name="yourID_guid"/>
</span>

Those two hidden inputs let you keep track of any file that was asynchronously uploaded.

6. Work on your web app so that it *does* handle file uploads to /Home/AsyncUpload (or whatever URL you’ve configured in step 4). The handler should save the uploaded file to disk, then return a unique token, such as a GUID or filename, to will identify the file you just uploaded. See the demo project for a simple way to do this using ASP.NET MVC.

7. When the containing form is finally submitted, check whether a file was sent with the request. This will happen if the user doesn’t have JavaScript enabled, as they’ll revert to traditional uploading behaviour. Also check for the hidden inputs called yourID_guid and yourID_filename – these will be populated if the visitor *does* have JavaScript enabled, and reflect any file that was uploaded asynchronously.

Further configuration

The asynchronous uploader plugin has plenty of properties you can configure in step 4 above:

Property Meaning Example
flash_url Location of swfupload.swf “/Scripts/swfupload.swf”
upload_url URL of the handler to which files will be asynchronously sent

Important: This is not the name of a directory or file on your server’s hard disk. It is the URL of a handler, such as an ASP.NET MVC action method, or a PHP page, or a classic ASP page, or an ASP.NET WebForms .ASHX handler, which will receive the file. It remains your job to implement such a handler and then save the incoming file to disk or database. For an example, see the ASP.NET MVC demo project at the end of this blog post.
“/Home/AsyncUpload”
file_size_limit Files above this size will be rejected before uploading even begins “3 MB”
file_types “Select files” popup will only show files of this type “*.jpg; *.gif”
file_types_description “Select files” popup will use this caption to describe the selectable file types “All images”
button_image_url Location of an image to be used for the “Choose file” button “blankButton.png”
button_image_width, button_image_height Dimensions of “Choose file” button 109
button_text Text that appears on the “Choose file” button "<font face=’Arial’ size=’13pt’>Choose file</font>"
disableDuringUpload Elements matching this jQuery selector will be disabled while an upload is in progress (useful to prevent form submission during async upload). “INPUT[type=’submit’]”
existingFilename Prepopulates the control with the name of a file already uploaded (useful when retaining state across multiple posts) “somefile.zip”
existingGuid Prepopulates the control with the arbitrary unique token you’ve given to a file already uploaded (useful when retaining state across multiple posts) “ec42555e-bfe7-45b0-87bf-36b1299f0398”
existingFileSize Prepopulates the control with the size, in bytes, of a file already uploaded (useful when retaining state across multiple posts) 548293
debug Turns on SWFUpload’s debugging console true

Demo project

The easiest way to understand all this is to check out a completed implementation. Here’s one written for ASP.NET MVC.

To compile and run this, you’ll need Visual Studio 2008 and ASP.NET MVC Beta. It saves asynchronously-uploaded files to the folder ~/App_Data/Files, giving each one a GUID as a filename. When you finally submit the form, it simply displays the filename and GUID of whatever file you uploaded. In a real app, you wouldn’t display the GUID to the end user, but would instead just use it to locate their file later.

kick it on DotNetKicks.com

88 Responses to jQuery Ajax uploader plugin (with progress bar!)

  1. Simon Taylor

    Great presentation on Saturday – it was really good to be talked through some real code rather than just shown a power point presentation :o ).

    Although I’m now very much a .NET developer, I’m only just getting into ASP.NET and my previous web development experience was very much JAVA based so find it really surprising that an MVC framework for ASP.NET is only just coming out when things like struts have been around for years.

    Maybe it’s because of my JAVA experience but this definitely seems a very natural and the *right* way of coding web applications. Have you had much feedback about why some people don’t like it? Dave Sussman in his presentation with Phil Winstanley mentioned that he didn’t like it although I didn’t (and probably should have) pick him up on it.

  2. Andy

    I often get asked about download plugins/controls in ASP.NET and MVC. (I realise browsers typically have some flavour of download management built in.) My dream to deliver what my colleagues want is a Silverlight multiple download tool with progress eg. a library of photos downloaded from a Digital Asset Management type app. Which also then begs the question, how easy would a Silverlight uploader be?!

  3. Pete

    I echo Simon Taylor’s comments – great presentation on Saturday at DDD, best of the day for me. I loved the fast pace you went at, it really kept me interested.

    Now, just off to pre-order that book of yours… :-)

  4. Jake Scott

    Thanks heaps! Very nice! Can’t wait to use this somewhere :)

  5. If flash is not installed, will it prompt the user to install? I did not have flash installed on my VM and was not notified I need to install flash.

  6. Does it work with Flash 10 and can you put more than one on a page?

  7. Steve

    @Andrew – to keep the code simple for the demo, I didn’t add Flash detection. It should be simple enough to combine this with jQuery Flash plugin (http://jquery.lukelutman.com/plugins/flash/). If Flash isn’t installed, you could either prompt to install it, or you could silently fall back to no-JavaScript style behaviour.

    @John S – yes it does work with Flash 10 (that’s what I’m running) and yes you can put multiple on a page.

  8. Andy Scott

    Hey Steve,

    Great post – would love an example of this “without flash” – that is jquery and just a pure MVC uploader ?

    Cheers,

    Andy

  9. Steve

    @Andy Scott – there isn’t really any way to do this without Flash (except very fiddly and fragile server-side upload monitoring plus client-side polling), because browsers offer no native API to monitor uploads.

  10. Pingback: Dew Drop - November 25, 2008 | Alvin Ashcraft's Morning Dew

  11. so, using flash to monitoring is better steve ? But how about http://www.bram.us/projects/js_bramus/jsprogressbarhandler/ I saw the nice progress bar, but the reason was not complete about how to implamentad it ..

    cool ! I digg this tutorial :) thanks steve

  12. Steve

    @Dr Emi – thanks for the link to the JavaScript progress bar. But notice that it’s *only* a widget for rendering a progress bar, and has nothing to do with uploading files. As I said, JavaScript has no native API for monitoring file upload progress. Wish it did.

  13. hi :
    i didnt try it yet , but its look nice , thank you ..

  14. I have tried your demo project. Works nice in FF3, bud it seems to have some problems in Opera. Have you checked that? (I can see only ‘Uploading…’ but the upload never completed. Second try later in Opera: ‘Sorry, your file wasn’t uploaded: Error #2038′)

  15. Steve

    @Pepa – that’s strange, because it works perfectly when I run it in Opera v9.62. Apparently Flash error #2038 can mean almost anything, though there are a couple of threads that describe it appearing when you upload a file bigger than your server’s max request length: http://swfupload.org/forum/generaldiscussion/208
    It may not be a browser issue, but something to do with server config instead.

  16. Nice! Can you provide us live DEMO on your site

  17. Dave

    When it gets to the server, I get a “could not parse” for the POST data. First time ever seeing that… this is in both Safari and Firefox 3 on the Mac. Has anyone gotten this working on a Mac?

  18. Steve

    @Dave – it works perfectly on Mac when I tried it (Leopard, Safari 3.1.2). I don’t have any other Macs to try it on, but I’d guess your issue must be server-side configuration. Have you tried running the ASP.NET MVC demo project?

  19. Dave

    @Steve – Glad to hear it! No, I haven’t tried the demo project (ASP.NET isn’t my thing). But knowing that it works is enough for me to keep working on integrating it into my Django site.

  20. Karthik

    I have placed all the code correctly. Now do I need to place the jquery.flash.js in current document? Second will I need any MVC Edition to be included in VS.Net 2008? Currently I do not have MVC Edition included in my VS.Net 2008 Version.
    I am not able to see any effect of Progress Bar when I put it in my existing code. Please help.

  21. Steve

    Karthik, if you’re going to use it with an ASP.NET MVC application, then yes you will need to install ASP.NET MVC on your computer. First download and install ASP.NET MVC, and then make sure you can run the demo project I’ve provided.

  22. Karthik

    But is not it possible to run it the same demo application without asp.net MVC? i.e. with .Net Framework 3.5 , VS 2008 and ASP.Net 2.0

  23. Steve

    Karthik, no, you need the ASP.NET MVC assemblies in your GAC, because I haven’t included them in the demo project.

  24. oori

    very nice plugin, thanks.
    small remarks:

    a. CORRECTION: file_types should be separated by ; and not comma (as in the above table), otherwise – doesn’t work..

    b. floating elements (like cluetip) hidden behind the flash uploader – to resolve this, added this line to your code (in line43, but anywhere under defaults works):
    button_window_mode: “transparent”,
    (exists in swfupload since v2.2)

    c. for anybody who wants to hide the flash button after successful upload, insert “width = 0;” in line 69 – inside the “upload_success_handler”. later on, the “swfu.setButtonDimensions(width, height);” will hide it for you. other forms (like display:none or visibility:hidden) will make trouble because in FF/IE of swfupload.

    thanks again for your post.

  25. Steve

    @oori – thanks for letting me know! That’s really helpful. I’ve updated the “file_types” info above. I’ll leave people to apply your points (b) and (c) themselves if they wish.

    I’m already using the “width=0″ trick to hide the button during an upload. After the upload completes, I make the button reappear so the user could select a different file if they changed their mind.

  26. KevinUK

    Is anyone using this with the MVC storefront example?

    When I step through the code it successfully sets _fileStore. Next it goes to the constructor in HomeController. Without stepping into the constructor if I wait a couple of seconds the swf component shows an alert box with error #2038.

    I have this demo application working and my configuration settings are correct as when I choose a file the progress bar appears and greys out the submit button.

    I also checked the save location is valid. Any ideas as to what seems to be timing out the swf?

  27. Steve

    Kevin, I wonder if you’re making the common mistake of thinking “upload_url” is the name of a folder to which the file is uploaded. It isn’t: it’s the URL of a handler (such as an action method) which receives the uploaded file. See the demo project to see how it works.

    If that is the confusion, I guess I really should have chosen a more descriptive name for “upload_url”.

  28. co.

    This code is instant favorite :)

    My only question is, does it recognize relative paths like “../test_dir”? It returns me error 405. I’m working in classic ASP.

  29. Steve

    Co, I can only guess that you’re misunderstanding in the same way that previous readers have done. Otherwise, I’m not sure what you’d be trying to do with relative paths. Please read the previous comments, specifically comment number 27.

    I have updated this blog post: about halfway through it, there’s now a big orange box entitied “Important”, which hopefully will make this point extremely clear.

  30. co.

    Thank you for prompt reply. I haven’t read it carefully :(

  31. Stu

    Great control – thanks. Has made my job much simpler now!
    Just a couple of issues though:
    1) the button_image_width doesn’t work for me.
    2) would be nice to have a property that only allows one file to be uploaded. So, once it has been selected, then the button disappears.

    thanks again

  32. Stu

    To allow jquery to access the guid and filename hidden inputs I had to change lines 14 and 15 of the jquery-asyncUpload-0.1.js so that the id was populated as well as name:
    container.append($(“”));
    container.append($(“”));

    thanks again…

  33. Stu

    ah, my previous post had the s c r i p t tags automatically taken out of it. Basically, set an id property in the same way as the name property is set.

  34. Dmitry

    I need to see files list in another div after uploading. I created a function listFiles() which calls jQuery ajax request and fills div. But when I insert fileList(); just before the $(function) code ends, I can see only standard HTML control. Any problem calling another function after uploading? Do you plan to do a success/error callback functions?

  35. Steve

    @Stu – I’m not entirely sure why you needed to do that (you can see another way of accessing the guid and filename hidden inputs on lines 56 and 57), but if it works for you, great!

    @Dmitry – check out the upload_success_handler and upload_complete_handler functions in jquery-asyncUpload-0.1.js.

  36. Dmitry

    @Steve – Thanks for reply.
    I tried to do that but I really don’t like an idea of making changes into your source code because of new versions which will be hopefully available in future. I may simply forget of what I have done before :)

  37. Dmitry

    I’m not a Javascript guru and I’m not sure if it’s done correctly but I tried to make some changes myself in jquery-asyncUpload-0.1.js file. Maybe you can improve this and include in future release?
    I did some changes right before “if (options)” line:

    var complete_callback = function() { };

    Within “if (options)” block -

    if (options.complete) complete_callback = options.complete;

    and in upload_complete_handler within “Success” block -
    complete_callback();

    Every time I need any function to be called after upload is complete, I just define some myFunction() and set it to “complete” parameter like this:
    $(function() {
    $(“#File1″).makeAsyncUploader({
    upload_url: ‘/Store/UploadFile/’,
    flash_url: ‘/Scripts/swfupload.swf’,
    button_image_url: ‘/Content/blankButton.png’,
    disableDuringUpload: ‘INPUT[type="submit"]‘,
    file_types: ‘*.jpg; *.bmp’,
    complete: myFunction
    });
    });
    Hope this doesn’t look too crazy :)

  38. this thing is just great.

  39. ari

    thanks for the plugin!
    the progress is realy good and the file is uploading.
    but,i got some problem.
    upload_success_handler
    donot invoke!

  40. ari

    *solved*
    i didnt sayed that i use ashx handler
    the only thing is the flash need to get some response.
    so:
    ctx.Response.Write(“ok”);
    ctx.Response.End();

  41. Steve

    @Ari – yes, that’s right – your handler has to return some response because that’s the value we’ll store in the hidden form field. Normally you’d return some unique value (rather than just “ok”), because then you can match up the subsequent form submissions with their previously uploaded files.

    In my demo, I generate a GUID for each upload, save the file on disk using the GUID as filename, and return that GUID to the browser. That’s how I can associate each form submission with the file the user previously uploaded.

  42. Lars Zeb

    Thanks for the example, Steve. I’ve learned a lot.

    One detail is bothering me. I wanted to increase the file size limit of the uploaded file. No matter what I change the file_size_limit in jquery-asycnUpload-0.1.js to, it has no effect. It seems like 3MB is hardcoded somewhere but I can’t find it.

    Do you have any idea how this might be changed?

  43. Steve

    @Lars, 3MB isn’t hardcoded, but what kind of error are you getting?

    If it’s the uploader saying “File exceeds maximum size”, then the uploader isn’t configured properly.

    If you get some other error, then it’s probably your server rejecting the upload. Check your server’s config and increase the maximum allowed request length.

  44. John

    Thanks for sharing this – very easy to implement!

    However, I get a 401 error when trying to use this within a secured (htaccessed) directory. Apparently, based on some brief Googling, this is a Flash issue. Has anyone found a workaround for this or a decent javascript based alternative?

    Thanks again,

    John

  45. Lars Zeb

    I got a “Sorry, your file wasn’t uploaded: Error #2038″. Finally read your warning about upload_url and changed /Home/AsyncUpload to /Import/AsyncUpload and got beyond that.

    Now I am getting null for both the two parms in the Post ActionResult (photo_guid and photo_filename). Can you point me to any utilities or methods I might use to debug the upload_success_handler method in jquery-asyncUpload-0.1.js?

  46. Steve

    @Lars – sorry, I don’t quite know what you mean by “Post ActionResult”. Have you checked the downloadable demo code to see how this works?

  47. Lars Zeb

    Disregard this last post. I figured out how to debug javascript and realized I had played with jquery-asyncUpload-0.1.js too much.

  48. mihai

    I’m using FF3.0.5 + Flash Player 10 + linux + lighttpd + php, and after i pick the file it says ‘Sorry, your file wasn’t uploaded: 400′. It says the same thing whether the upload_url points to a working page or to a non working page. I tried one of the demos from the swfupload site and it seems to work fine, so my biggest bet is it’s a flash player 10 + lighttpd problem…

    I’ll try switching to apache and reply again.

  49. mihai

    Ok, i switched to Apache, and it seems to work fine. Just that the field set is ‘Filedata’, and not what i was expecting (the name of the file input tag).

  50. Selwyn

    I Have implemented the same code as in the demo but i am returning the image path instead of the guid i have uploaded the image through the image upload service works fine in IE 7 but giving error in crome,FF3.0 ,safari
    but your demo code is working in all the browsers what might be the issue

  51. Nicolas Cadilhac

    My web site uses authentication. In all y action methods, once logged in, User.Identity.IsAuthenticated returns true. But in the Upload action, it returns false, preventing me to construct a path containing the user name. Any idea?

  52. Steve

    @Nicholas – a quick bit of research suggests there’s a bug in the Flash plugin for Firefox (but not in the one for MSIE) which means it doesn’t send cookie information when uploading files. See: http://www.visible-form.com/blog/flash-file-upload-and-session-cookies/

    You could use the solution shown on that web page, but I would warn you that if you also have an XSS bug anywhere on your domain, then including a session ID in the HTML (as they do) gives attackers a means of bypassing HttpOnly protection against session hijacking.

  53. Nicolas Cadilhac

    Thanks. I think I will avoid uploading in a user folder.

    That said, did you already consider extending your script to allow multiple uploads? It would create a list of attachments on the page with a “X” for each so that you could change your mind and delete an already uploaded file. The open dialog box could allow the user to select a batch of files in one pass…

  54. Steve

    @Nicholas – the underlying SWFUpload technology certainly supports selecting and uploading multiple files at once, so it should be possible to extend the script in that way. That’s not something I will personally have a reason to do any time soon, but perhaps you’d like to give it a try.

  55. Nicolas Cadilhac

    ok, I was asking just because my skills in javascript are not good enough (yet). Maybe a good opportunity to learn more. If someone wants to try to extend the script though, this is welcome.

  56. Steve, this is fantastic – just what I was looking for. Kudos and thanks for your work!

  57. Alexander Benjamin

    Two things:

    could you post .fla file.
    I m having trouble with authentication because flash player doesn t send session cookies.
    Is there any real work around?

  58. Steve

    > could you post .fla file
    The uploader is written using SWFUpload. You can download SWFUpload’s FlashDevelop project file and source code from http://code.google.com/p/swfupload/

    > I m having trouble with authentication
    Yes, that is awkward. I’m not aware of any great workaround, but check out comment #52 above for one possible way forward.

  59. M

    Does this support custom error messages?

    I perform a couple of security checks before uploading a user’s photo, and I’d like to show my users what happened if things go wrong.

  60. Steve

    @M – Sorry, but I’m not really sure what you’re asking for. This is just a component for turning a traditional file upload box into one with a progress bar. If you need any other application functionality then you should implement that separately.

  61. Dave

    I’m implementing this without using MVC for the handler. Can you provide more detail on what the “handler” would return? Is the return an http header? I’m unclear as to what is being returned from the handler. Do you happen to have an example of a handler in PHP?

  62. Hey Steve … great plug in! One question. Is there anyway to add custom request parameters?

  63. Steve

    @Dave – The handler should return any nonempty string that you want to use to identify the upload. It might be a GUID or a primary key value or anything you like. Just return some arbitrary constant string if you want. This should go in the response body (not in an HTTP header).

    In my demo, I’m saving the asynchronously uploaded file on disk using a GUID filename, and returning the GUID from the handler. The plugin automatically keeps a record of that GUID and submits it with the main form when that gets submitted synchronously. That’s how I know which uploaded file corresponds to which form submission. I don’t have a PHP example unfortunately, although if you create one then please make a blog post about it, then I can direct future PHP enquiries to you :)

    @Chris – Yes, there certainly is. Just add them to the config object as follows:

    $(function() {
        $("#photo").makeAsyncUploader({
            upload_url: "/Home/AsyncUpload",
            flash_url: '/Scripts/swfupload.swf',
            button_image_url: '/Content/blankButton.png',
            disableDuringUpload: 'INPUT[type="submit"]',
            post_params : { 
                "uploaded_by" : "bobby",
                "favourite_colour" : "Beige"
            }
        });
    });    

    Note that this plugin is built on SWFUpload, so there are many more things you can do, as documented at http://demo.swfupload.org/Documentation/

  64. Pingback: Top 50 Ajax Tools, Scripts & Solutions that will rock your world. | TheGermz.com

  65. How can we achieve the same thing using WebMethods in asp.net

  66. Thanks for the great plugin Steve. It is working great for me.

    Here is a question for you: I am renaming the uploaded file in an AsyncUpload PHP script. The original filename is returning via “file.name” in the upload_success_handler, not the new filename. Any idea how to have it return the new name?

    Thanks!
    Matt.

  67. Steve

    @Matt – I’m afraid I don’t know what you mean by renaming the file. If that’s something you’re doing on the server then it won’t be picked up automatically on the client. Could you clarify what sequence of things you’re doing?

  68. @Steve – In the PHP script that handles the upload (upload_url: “upload.php”) I am moving the uploaded file to a folder. At the same time I am renaming the file. The file uploads just fine, with the new name. The problem is that in the Javascript the original file name is return via the upload_success_handler. So, after uploading the file the HTML is updated to says “Uploaded OriginalFilename.jpg”, not “Uploaded NewFilename.jpg”.

    Does that help??? THanks!

  69. Mike

    I tried to get work the script with php but anything it says is 404… i dont understand the handler thing, is this the file like uploader.php where it reads the file?
    move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)
    ?

  70. I figured out about the 404, I should set upload_url to “../uploader.php”
    the next problem was a 2038 error, solution: I should use the name “Filedata” in php (and not my own name set in the js script) like this:

    move_uploaded_file($_FILES['Filedata']['tmp_name'], “./upload/blabla.jpg”);

    next problem was a “never ending upload”, solution: the uploader.php should echo(“something”); to let the js script know the upload is ready.

    one little problem is using it with opera: I need to press the “Choose file” button twice to open the file dialog window. Any idea how to solve it? I click on the button once and it gets blue, then if i click again, the dialog appears… maybe some focus issue.

    beside this it works, thanks for the script Steve :)

  71. David W

    Does the upload_url need to be an absolute path? I had my PHP upload handler file in the same directory as the JS file and it gave me 404 errors. Then I put full absolute path (for me not an ideal solution) and suddenly it worked, but the path to the Flash file and the button image handled relative paths just fine. Any ideas?

    @ Mike … you say you had the same/similar problem with the 404, and I tried doing the same but got no love. So I tried an absolte path and there you go!

    AS for the PHP part for the handler, this also confused me endlessly even though it’s simple. I just didn’t know how it worked. Until Mike’s post (so thanks Mike :) )

    … should do the trick.

  72. David W

    ===== BEGIN PHP =========
    $uploaddir = ‘/var/www/uploaddirectory/’;
    $uploadfile = $uploaddir . basename($_FILES['Filedata']['name']);

    if (move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadfile)) {
    echo basename($_FILES['Filedata']['name']);
    } else {
    // nada … it didn’t work!
    }
    ===== END PHP =========

  73. David W

    @ Steve – Thanks for the script mate, works very well :) I can give you a PHP example if you like, it’s very simple. Tried to paste it in but your comment stripped it out .. sneaky sneaky :) Let me know!

  74. Mike

    here is something I get in Django.. I find it a bit odd why i’m getting this in firebug when I queue up a image

    uncaught exception: Invalid function name: ReturnUploadStart

  75. Dan

    This script is great, but i had one question.

    Is there any way i can have this script running on my web server, but have the files it uploads automatically go to an ftp server somewhere else?

    the trouble i’m having is it seems to make the user wait for the file to be transfered to the web server first, and then it moves it through php’s ftp functions to the FTP server, which makes the user wait twice – which is a problem with larger files….

    any suggestions?

  76. Steve

    @Dan – perhaps your server-side code can return a result to the user immediately, close the response, and then continue to process the request by copying the file to the FTP server. That way the user wouldn’t need to wait for the FTP transfer to complete. I could tell you how to do this in ASP.NET but I’m afraid I have no idea how to do it in PHP.

  77. Jack FInger

    Hi, great plugin, really thanks, but I have small problem:
    when I’m uploading 180MB large file, it shows me status “Uploaded”, but nothing is saved. With smaller files the same script runs (e.g. 100MB). Server is configured well. What to do? Thanks.

  78. bill

    Hi Steve, thanks so much for sharing your hard work. BTW, I was in Bristol once when I was just a lad and had the opportunity to kick it around with the Bristol Rovers. But I digress… :)

    Has anyone tweaked this to upload multiple files? I attempted but have failed miserably.

    Thanks for any help!
    Bill

  79. Hemoglobina

    Hello Steve. As many have already said, thank you for the time you put into this.
    Everything is working great, except when I try to change the CSS for the DIV.ProgressBar.
    If I change the last line to: display: inline-block;
    The entire upload process hangs.
    What could be the reason for this behavior?
    Thank you for your support,
    Hemoglobina

  80. Steve

    @Jack – It must be some problem to do with your web server configuration. Nothing on the client side changes its behaviour depending whether the file is 100MB or 180MB. Your server must be configured to reject POST requests above a certain length.

    @Bill – I haven’t heard of anyone enhancing the script in that way but I’ll email you if I find out that anyone has.

    @Hemoglobina – changing the CSS won’t affect the upload process (or at least I can’t see any reason why it would). Perhaps you just aren’t getting the same visual feedback because the progress bar is no longer displayed correctly.

  81. Chris

    Having a problem,
    If I upload a 25 meg file, it uploads fine my action on my controller gets hit, it saves the file returns the guid and the Success and Complete events get called.

    If I upload a 150 Meg file, it uploads fine, my action on my controller gets hit, it saves the file returns the guid, but the Success and Complete events never occur so it never finishes.
    This is in FF 3.0.7

  82. Chris

    Steve,
    Love the stuff.

    Using your sample MVC app:

    I tested it in Safari, FF and IE 7
    I added to the system.web area of the Web.config:

    And I added to the makeAsyncUploader call:
    , file_size_limit: ’1024 MB’

    In ie 7 I get a Error ‘SWFUpload_0′ is undefined.
    In FF and Safari I get the problem I mentioned in the previous message, where files under 100 mb work fine, files of=ver 100mb seem to upload to the server fine but never finish on the client.

  83. Chris

    Ahh removed my xml, here is what I added to web.config:
    <httpRuntime maxRequestLength=”999999″/>

  84. Chris

    Weirder and Weirder
    Change the order of the parameters to (moving file_size_limit up):

    upload_url: “/Video/AsyncUpload”,
    flash_url: ‘/Scripts/swfupload.swf’,
    button_image_url: ‘/Content/blankButton.png’,
    file_size_limit: ’1024 MB’,
    disableDuringUpload: ‘INPUT[type="submit"]‘

    And for files larger then 100 mb it now works.
    (Though IE 7 is still broken)

  85. ed

    Seems like the upload handler isn’t getting called when I try this code out… Here is what I have:

    $(function() {
    $(“#myFile”).makeAsyncUploader({
    upload_url: “uploader.php”,
    flash_url: ‘swfupload.swf’,
    button_image_url: ‘blankButton.png’
    });
    });

    [...]

    And for “uploader.php”:

    What should happen is “hello!” should get printed, then throw an error… neither of these happen. Am I doing something wrong here?

  86. ed

    Contents of uploader.php:

    echo(”hello!”);

    echo ;

  87. Dorry

    Hey!
    How enable multiupload in this Demo project?

  88. Steve

    @Dorry, I haven’t written support for uploading multiple files concurrently in this demo project. To do this yourself, read the SWFUpload documentation and then enhance jQuery-asyncUpload-0.1.js suitably.