AJAX Upload progress monitor for Commons-FileUpload Example

Don’t laugh .. I did not get any comments from my previous post (normal, nobody reads this blog except me :-) ), so I decided to take the time to put together a little sample of a Java AJAX file upload progress bar example.

For people who never used DWR, it can also serve as a nice example of how simple it is to use.

The example has been kept to the strict minimum to be self explanatory and it not supposed to be used as is .. (java code is a JSP aarrrggg …).

I also added a delay during the upload so that you get a chance to actually see the progress bar move when the server and the client are on the same machine.

[code lang="java"]UploadListener listener = new UploadListener(request, 30);[/code]
To run the example, just place the war file in your favorite servlet engine’s deployment dir.

Here is a screenshot of the example in action :

Here is the war file : ajax-upload-1.0.war (the war includes all sources and a build file)
And remember, this is an example to demonstrate and understand how all this works and is not supposed to be used as is.

P.

63 Responses - Leave yours here.

  • Excellent Work Sir. In my curiosity, I simply downloaded the WAR and tested it. Needless to say it didn’t worked. Everything worked fine but could not find where did the files got uploaded? I am still going thru the src but will take time.

    Like everyone else, I sincerely worship APACHE and think of one utility which should be in Struts.

    Dynamic Row Addition – UI Level.

    And the other one is what you have just developed.

  • Thanks for your comment. The code should work fine. To get the files actually uploaded just read the Jakarta commons File Upload API to see how to go further. It’s rather straightforward.

    The JSP in the example just takes care of parsing the request and does not do anything with the files ..

  • Exactly what I’ll need. I haven’t had time to investigate how to solve it yet though. This will save me a lot of time. Thanks a million for sharing you knowledge!

  • If used with struts, instead of using upload.jsp as action, you need to provide a new MultipartRequestHandler in struts-config.xml ala

    The ExtendedMultiPartRequestHandler can be the normal one supplied with struts with the following changes;

    replace the line;

    DiskFileUpload upload = new DiskFileUpload();

    with

    UploadListener listener = new UploadListener(request, 30);
    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    ServletFileUpload upload = new ServletFileUpload(factory);

    plus additional imports as in upload.jsp.

    Very nice example btw, thx! :)

  • Oops, the comment form stripped my xml code.. Add to struts-config.xml;

    <controller multipartClass=”com.example.ExtendedMultipartRequestHandler” />

    Where that class is your augmented org.apache.struts.upload.CommonsMultipartRequestHandler impl.

  • A few comments; the setup doesn’t work properly if the debugDelay is set to 0;

    = new UploadListener(request, 1);

    Furthermore, the setup seems to trigger the firefox infinite javascript loop detector when the progress bar reaches 100% and the server takes a while to process the uploaded file before sending back a new page.

  • hi,
    It is really useful for newbies like me, can u please tell me how to upload the file.but its not working I copied that war file in webapps in my tomcat5.x but its not working some erros is getting displayed.Thanks in advance

  • Thanks.

    Very usefull and exactly what i needed.

  • Hi All,

    This is really cool..
    but
    Can some body send me the exact changes needs to be done in order to upload the files on server.

    kaante

  • Great example and the source was very self explanitory. However, is it possible to upload the data without being redirected to a results page? When the upload is completed I want to remain on the page but have the progress bar disappear.

  • Hi Torgier,

    Can you supply the struts code in a war file?

    Regards

  • Hmm, you need in struts-config.xml;

    ExtendedMultiPartRequestHandler: Take the source of the existing struts CommonsMultiPartRequestHandler, see http://struts.apache.org/struts-action/apidocs/org/apache/struts/upload/CommonsMultipartRequestHandler.html

    In the handleRequest() method, make sure the setup code reads;

    UploadListener listener = new UploadListener(request, 1);
    log.debug(”uploading file with optional monitoring..”);

    // Create a factory for disk-based file items
    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);

    ServletFileUpload upload = new ServletFileUpload(factory);

    In your form bean;

    private FormFile mediaFile;
    public FormFile getMediaFile() {return mediaFile;}
    public void setMediaFile(FormFile mediaFile) {this.mediaFile = mediaFile;}

    in your jsp file;

    #progressBar { padding-top: 5px; }
    #progressBarBox { width: 350px; height: 20px; border: 1px inset; background: #eee;}
    #progressBarBoxContent { width: 0; height: 20px; border-right: 1px solid #444; background: #B0C9E7; /* plainNegativeBold */ }

    ‘>

    function UploadMonitor() { }
    UploadMonitor._path = ”;
    UploadMonitor.getUploadInfo = function(callback) {
    DWREngine._execute(UploadMonitor._path, ‘UploadMonitor’, ‘getUploadInfo’, callback);
    }

    in your html form;

    Did I miss anything?

  • Works very smoothly except in the case where a large upload exceeds a configured limit and SizeLimitExceededException is thrown.

    In this case, the progress bar remains at 0 and there is a long delay, presumably because the browser is still sending the data over the open connection, unaware that the receiving servlet had terminated with the exception.

    Can you think of any way to gracefully abort the upload in this case? I’ve tried UploadListener.error(), but it seems to have no effect.

  • Hi,i used your ajax-upload progress bar.But you included

    dwr/interface/UploadMonitor.js
    dwr/engine.js
    dwr/util.js

    İ can’t see this files in your exam. war.

    but your example is running?.How and how can i entegtared this samples to my project?

  • I was not able to find dwr/interface/UploadMonitor.js and other required .js files. Not sure if everything was downloaded or not..Can you suggest me where to get those js files?

    thanks,
    Sri

  • Alex,

    Very nice DWR adaptation. Thanks for the open source spirit and your working AJAX file upload sample. Sweet!

    John

  • Kadir and Sri,

    The reason why you don’t see the files

    dwr/interface/UploadMonitor.js
    dwr/engine.js
    dwr/util.js

    is because they are dynamic files created by the dwr servlet. when you go to any url that starts with http://your webapp>/dwr/* it is redirected to the dwr servlet which in turn creates all of the javascript files dynamicly, depending on your settings in the dwr.xml file.

    I hope that answers your questions, I am still very new to dwr, if you have more questions I would suggest checking out the dwr website, they have a nice set of docs.

    Pierre,

    Thanks for the cool example, I was looking for something just like this.

    Ken

  • I have run the example and can not find the files that it uploads. Where is the setting for the location of the uploaded files?

    Thanks,

    Jay

  • disregard my previous message. My mistake if I only read all the comments stating that it is not saving the files. sorry

    Jay

  • F.Y.I.

    I have updated the code that Pierre-Alexandre Losson wrote so that it works with struts, doesn’t change pages when file is finished uploading, and it shows an example on how to save the file once it is uploaded. I have the code as well as a little write up on this page.

    I looked at the comments and used some of the suggestions that people left, and hopefully solved some of the questions that others have left.

    Feel free to check it out and let me know what you think..

    http://kencochrane.blogspot.com/2006/03/ajax-struts-file-upload-progress-meter.html

  • [...] This has been done before with PHP (AJAX upload progress meter for PHP) etc but I needed something a little different because I wanted to upload a file and then have it loaded into a database. I looked around and found that someone had already made something that used the commons file upload package to do the upload part (AJAX Upload progress monitor for Commons-FileUpload Example). It wasn’t exactly what I was looking for but it a good start. [...]

  • hello thanks for this useful program but i recive the project in .zip not .war how can i use it ?

  • got the javascript exception on the firefox 1.5, anybody has the same problem?

  • I use ajax-upload-1.0.war in local.
    But progress bar is not work.
    I use browser is Internet Explorer 6 sp2.

  • Anyone have try the Struts version on : http://www.ajaximpact.com/detail_Articles.php?id=123

    it seems to have a problem with the class ExtendedMultiPartRequestHandler. Here is the error :
    net.kencochrane.upload.ExtendedMultiPartRequestHandler must be a subclass of org.apache.struts.upload.CommonsMultiPartRequestHandler

    Anyone know how to correct that ?

  • Thanks for this code,
    I tested the code, it worjed fine, but when I tried to integrate it in my project using jsf,spring, and hibernate, i got en error : it can not doing parseRequest :
    java.lang.NoSuchMethodError: java.util.List org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(org.apache.commons.fileupload.RequestContext)

  • Thanks a lot for this, it is just what I need.
    I’ve made the following modifications which others might find useful:

    1. Make the upload form target a hidden iframe so the upload page doesn’t go away

    2. Modified upload.js#updateProgress(uploadInfo) so that it shows a nice upload complete message when its done.

    Thanks again.

  • Works like a charm in our CMS system now.

    Now when the users upload videos of several hundred megabytes they see a progress.

    Thanks a lot.

  • I would like to use fileUpload from a java applet/java application. However, I’m not sure how to construct the http requests to be sent to an upload servlet.

    I looked at index.jsp for ideas on how to construct the requests, but the JSP handles sending of files with custom input tags: file.

    Could you please let me know how to add file objects to HTTP requests manually/programatically.

    Thanks for your help,

    Tammy

  • Have issues when running the upload. the status bar process complains that UploadMonitor is undefined. I have read through the above list of comments and have realize that it is dynamic therefore I cannot see it. My question is what would cause it to not work. I and using
    Apache Tomcat/5.0.28 with jdk1.5.0_05. Any help would be greatly appreciated. Thanks in advance

    Sean

  • More Detail:

    SEVERE: Creator: ‘NewCreator[UploadMonitor]‘ for UploadMonitor.js is returning n
    ull for type queries.

    Servlet.service() for servlet dwr-invoker threw exception
    java.lang.SecurityException: No class by name: UploadMonitor

  • Im having the same problem as Sean. Everything works fine when i try the .war in the webbapps folder. Im trying to move the files to another folder to get a better structure with an existing website.
    I get the “done” message after file upload but no activity on progressbar during transfer.
    I must have missed something simple, some path perhaps, but I can’t figure out what. Anyone familiar with the problem and the solution?

  • Looking forward to the answer to Tammy’s question. Is there an equivalent for an applet?

  • Good work!
    But is it possible to get the source code please?§!

    Thanks!

  • WAIT! THIS TECHNIQUE DOES NOT ACTUALLY WORK UNLESS IT IS PERFORMED LOCALLY. When hosted on a remote server, the process will still not provide any feedback until the upload is complete. Please see the following tutorial for a better understanding of the issue. It requires that a Filter be placed before the Servlet that processes the upload.

    http://today.java.net/pub/a/today/2006/02/09/file-uploads-with-ajax-and-jsf.html

    Ignore the faces part if you want, but the Filter/Servlet combo is required!

  • It very cool.I need some information about index.jsp but in uplaod.jsp request.getParameter(”file1″)=null.How can I get parameters in HttpServletRequest in upload.jsp?

  • hi, thanx for u good work at first!
    I v read u code and have a question. How can u get the total size of a file before it is not upload-completed yet? the code below is your way to solute it,right?
    //
    totalToRead = request.getContentLength();
    //
    but i still cannot catch it…can u explain it for me ? thanx a lot.
    yours.

  • Is it possible to have upload for each file separately and thus to track the status of that upload associated with Single file. In the current page multiple files can be uploaded but upload is triggered at one shot only. In our application we need upload of multiple files which can be triggered separately.

  • [...] This has been done before with PHP (AJAX upload progress meter for PHP) etc but I needed something a little different because I wanted to upload a file and then have it loaded into a database. I looked around and found that someone had already made something that used the commons file upload package to do the upload part (AJAX Upload progress monitor for Commons-FileUpload Example). It wasn’t exactly what I was looking for but it a good start. [...]

  • Hi am probably being thick here, but i can’t figure out how this progress bar work at all. I’ve downloaded the WAR file. Then extracted it using RAR (Was that suppose to be done???)
    Then in there i have a lot of files most of them being .jsp. What is the next step to get this thing working??
    Am desperate i’ve looked all over the place for an upload progress bar with it percentage but none of them was working correctly (CGI, or PERL) stuff.
    HELP PLEASE>

  • Like post #36 Yangjinglong said, “request.getParameter(”file1″)=null”. I changed the METHOD to GET and request.getParameter(”file1″)=”" but then the DWR servlet crashes so it must rely on the POST Method. Why does the DWR strip the METHOD?

    Post #28 André Schild, how did you name your uploaded files?

  • [...] The P Blog » AJAX Upload progress monitor for Commons-FileUpload Example AJAX Upload progress monitor for Commons-FileUpload Example using DWR (tags: ajax upload java dwr file javascript programming web2.0) This entry was written by Vinny and posted on August 12, 2006 at 11:18 pm and is filed under Daily Links. Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL. [...]

  • [...] The P Blog » AJAX Upload progress monitor for Commons-FileUpload Example AJAX Upload progress monitor for Commons-FileUpload Example using DWR (tags: ajax upload java dwr file javascript programming web2.0) Tags:Bookmark this page at:These icons link to social bookmarking sites where readers can share and discover new web pages. [...]

  • Actually, you do not need to use AJAX there. Upload progress could be done without refreshing upload page and with no AJAX. Solution is quite simple – just some JS will be needed. You can take a look at our demo: http://www.sibsoft.net/xupload.html

  • oh!it’s very cool!but when i use this code :

    at the other domain such as http://localhost/upload.jsp,
    the proplem is that the progress bar is not showing at the first!but refresh the upload.jsp ,it work fine!:

  • where i can view the downloaded files in server

    please explain me

  • Please tell me how to get access to the uploaded files so that i can store them in the database.

    Some sample code explaining where to plug in data for the same would be really helpful

    Thanks
    Rohit

  • Nice stuff! Unfortunately not using Tapestry :-(

  • Hi,

    Nice sample. Everything is working fine. But I tried to find the path where the uploaded files are saving, could not find it. Can u please help me to find the saving path?

    Thanks,
    Mufee.

  • Hi,
    I’m also new in dwr…
    Every thing work right until i’m trying to connect the dwr function to a real button in my application…
    When i’m doing it when i’m pressing the button i’m getting a message that the button can’t recognize the class…
    Anyone?

  • Hi Luke,
    I am using DWR in my project.In your post, you are saying that you changed method from POST to GET. Please may I know how to do that.

    Thanks in advance.

  • hi,

    please give examples to use the file uploader in a spring application

  • Thanks for the info. It’s a cool add on to an already working file upload solution. I meant about the progress bar. Its really neat.
    Thanks

  • i use tomcat5.0 as web container but it does not work right,report errors:
    信息: retrieved system configuration file: java.io.ByteArrayInputStream@bbbd0e
    2007-9-6 17:25:24 uk.ltd.getahead.dwr.util.CommonsLoggingOutput info
    信息: Missing class for creator ‘pageflow’. Failed to load uk.ltd.getahead.dwr.create.PageFlowCreator. Cause: Beehive/Weblogic Creator not available.
    2007-9-6 17:25:24 uk.ltd.getahead.dwr.util.CommonsLoggingOutput info
    信息: Missing classdef for creator ’spring’. Failed to load uk.ltd.getahead.dwr.create.SpringCreator. Cause: org/springframework/beans/factory/BeanFactory
    2007-9-6 17:25:24 uk.ltd.getahead.dwr.util.CommonsLoggingOutput info
    信息: Missing classdef for creator ’script’. Failed to load uk.ltd.getahead.dwr.create.ScriptedCreator. Cause: org/apache/bsf/BSFException

  • ah~the uploaded files were stored in tomcat’s home “temp” dir but the name end with tmp.

  • I am trying to use this progress bar implementation in my own web application which has it’s own file upload part. But I couldn’t find some of the .js files that has been used in the .jsp pages of the web upload sample given above. Where can i get those UploadMonitor.js, engine.js, util.js files and all.

    Any help will appreciated greatly.

    thank you,
    Bhuvana.

  • I got the source code but unable to deploy in tomcat 5.0. Do I have to configute all the classpath..Plz do reply.

  • Thank u very much sir,
    I am very late to reply this forum,becoz I am a beginner in DWR
    Wonderful

    Please help me if u have more tutoyials
    Thanks
    Vishnu

  • Hi, Thanks for your tutorial .. it helps me a lot :)
    anyway I tried to copy upload.jsp into some servlet, and it’s not working.
    anyone had tried before ?

    or maybe this is why you wrote like this
    “The example has been kept to the strict minimum to be self explanatory and it not supposed to be used as is .. (java code is a JSP aarrrggg …).”

    ;p

  • I was not able to find dwr/interface/UploadMonitor.js and other required .js files. Not sure if everything was downloaded or not..Can you suggest me where to get those js files? .i want to use this example in my project.pls help me.

  • Hi plosson!!

    Thanks a lot for a such a nice piece of working example but I have a few problems, if you or somebody can help me.
    Actually the from action has been set to “upload.jsp” but in my spring-driven application I want to send my JSP directly to the controller, let me tell you the options I have tried out,

    1- I didn’t set the action for this form after placing the java code inside “upload.jsp” into the targeted controller, so it went directly to my controller (which I wanted it to) but the progress bar never moved.

    2- I kept the action to “upload.jsp” and did a jsp:fwd to my controller.The progress bar ran ok but the controller lost my model object being forwarded from the JSP.

    I have already spent lots of time on it trying various ways but to no avail, please can you help me out a little here?

    Cheers,
    Kamran.

  • Thanks for this. Just what I needed. I’m not done implementing this in my application yet, but after playing around with it, it seems simple.

  • file upload developer

    December 4th, 2009 at 3:03 am

    I am using apache file upload libraries. Have it running beautifully, except for one problem: For files that exceed specified limit we want to return immediately. The browser keeps sending data even though the servlet has closed the response stream and returned. This is a major issue for us as this experience is not acceptable to business.
    I see a similar post above too. Anyone figured this? Apparently browser and server are still communicating even though the application has responded.

Leave a comment

Your email will not be published. Required fields are marked *.