Wednesday, June 20, 2012

File Upload with Spring and jQuery (Part 5)

Review

We have just completed our application! In the previous sections, we have discussed the functional specs, created the Java classes, declared the configuration files, and wrote the HTML files. In this section, we will build and run the application using Maven, and show how to import the project in Eclipse.


Running the Application

Access the source code

To download the source code, please visit the project's Github repository (click here)

Building with Maven

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn tomcat:run
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'tomcat'.
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from central
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from snapshots
    [INFO] ------------------------------------------
    [INFO] Building spring-fileupload-tutorial Maven Webapp
    [INFO]    task-segment: [tomcat:run]
    [INFO] ------------------------------------------
    [INFO] Preparing tomcat:run
    [INFO] [apt:process {execution: default}]
    [INFO] [resources:resources {execution: default-resources}]
    [INFO] [tomcat:run {execution: default-cli}]
    [INFO] Running war on http://localhost:8080/spring-fileupload-tutorial
    Jun 20, 2012 8:35:14 PM org.apache.catalina.startup.Embedded start
    INFO: Starting tomcat server
    Jun 20, 2012 8:35:14 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
    Jun 20, 2012 8:35:15 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    Jun 20, 2012 8:35:17 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Jun 20, 2012 8:35:17 PM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    
  5. Note: If the project will not build due to missing repositories, please enable the repositories section in the pom.xml!

Access the Entry page

  1. Follow the steps with Building with Maven
  2. Open a browser
  3. Enter the following URL (8080 is the default port for Tomcat):
    http://localhost:8080/spring-fileupload-tutorial/upload

Attach a file

  1. Click on "Add a file"
  2. Browse for a file and add it. Check the logs and you should see something similar to the following:
    [DEBUG] [tomcat-http--24 02:15:20] (TraceInterceptor.java:writeToLog:21) Entering UploadController.upload(org.springframework.web.multipart.commons.CommonsMultipartFile@d1258b)
    [DEBUG] [tomcat-http--24 02:15:20] (UploadController.java:upload:43) Writing file to disk...done
    [DEBUG] [tomcat-http--24 02:15:20] (TraceInterceptor.java:writeToLog:21) Leaving UploadController.upload(): [UploadedFile [name=Tulips.jpg, size=620888, url=http://localhost:8080/spring-fileupload-tutorial/resources/Tulips.jpg, thumbnail_url=null, delete_url=null, delete_type=null]]
    

Attach multiple files

  1. Click on "Add another file"
  2. Browse for files and add them. Check the logs and you should see something similar to the following:
    [DEBUG] [tomcat-http--26 02:15:42] (TraceInterceptor.java:writeToLog:21) Entering UploadController.upload(org.springframework.web.multipart.commons.CommonsMultipartFile@7783ea)
    [DEBUG] [tomcat-http--26 02:15:42] (UploadController.java:upload:43) Writing file to disk...done
    [DEBUG] [tomcat-http--26 02:15:42] (TraceInterceptor.java:writeToLog:21) Leaving UploadController.upload(): [UploadedFile [name=Hydrangeas.jpg, size=595284, url=http://localhost:8080/spring-fileupload-tutorial/resources/Hydrangeas.jpg, thumbnail_url=null, delete_url=null, delete_type=null]]
    [DEBUG] [tomcat-http--27 02:15:42] (TraceInterceptor.java:writeToLog:21) Entering UploadController.upload(org.springframework.web.multipart.commons.CommonsMultipartFile@85ec1b)
    [DEBUG] [tomcat-http--27 02:15:42] (UploadController.java:upload:43) Writing file to disk...done
    [DEBUG] [tomcat-http--27 02:15:42] (TraceInterceptor.java:writeToLog:21) Leaving UploadController.upload(): [UploadedFile [name=Jellyfish.jpg, size=775702, url=http://localhost:8080/spring-fileupload-tutorial/resources/Jellyfish.jpg, thumbnail_url=null, delete_url=null, delete_type=null]]
    

Upload the files

  1. Click on "Upload". Check the logs and you should see something similar to the following:
    [DEBUG] [tomcat-http--30 02:16:20] (TraceInterceptor.java:writeToLog:21) Entering UploadController.message(Message [owner=John Smith, description=These are my files. I owned them., filename=Tulips.jpg,Hydrangeas.jpg,Jellyfish.jpg])
    [DEBUG] [tomcat-http--30 02:16:20] (UploadController.java:message:33) Service processing...done
    [DEBUG] [tomcat-http--30 02:16:20] (TraceInterceptor.java:writeToLog:21) Leaving UploadController.message(): StatusResponse [success=true, message=Message received, ]
    

Note:

When adding a file via the "Add a file" link, the file is automatically uploaded to the backend. The backend responds with an object containing the filename (and other file details). When you click on the "Upload" button, the form data is sent along with the filename. The file itself is never uploaded in this second step because it's already in the server!

Import the project in Eclipse

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn eclipse:eclipse -Dwtpversion=2.0
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'eclipse'.
    [INFO] org.apache.maven.plugins: checking for updates from central
    [INFO] org.apache.maven.plugins: checking for updates from snapshots
    [INFO] org.codehaus.mojo: checking for updates from central
    [INFO] org.codehaus.mojo: checking for updates from snapshots
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from central
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from snapshots
    [INFO] -----------------------------------------
    [INFO] Building spring-fileupload-tutorial Maven Webapp
    [INFO]    task-segment: [eclipse:eclipse]
    [INFO] -----------------------------------------
    [INFO] Preparing eclipse:eclipse
    [INFO] No goals needed for project - skipping
    [INFO] [eclipse:eclipse {execution: default-cli}]
    [INFO] Adding support for WTP version 2.0.
    [INFO] -----------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] -----------------------------------------
    
    This command will add the following files to your project:
    .classpath
    .project
    .settings
    target
    You may have to enable "show hidden files" in your file explorer to view them
  5. Open Eclipse and import the project

Conclusion

That's it! We've have successfully completed our file upload application with Spring and jQuery-File-Upload plugin. We've learned how to setup an HTML form for file uploads with AJAX-like experience.

I hope you've enjoyed this tutorial. Don't forget to check my other tutorials at the Tutorials section.

Revision History


Revision Date Description
1 June 20 2012 Uploaded tutorial
2 June 26 2012 Corrected wrong entry url
3 June 27 2012 Corrected wrong entry url again

StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: File Upload with Spring and jQuery (Part 5) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

25 comments:

  1. Thanks for the example
    A few things:
    a) on the tutorials menu, the first link "File Upload with Spring and jQuery (Part 1)" links to "Email with Spring and SendGrid (Part 1)" instead of the intended one.
    b) i downloaded the code, follow the whole tutorial but when tried to run it (either mvn tomcat:run, when deploying the generated .war into a standalone tomcat or mvn jetty:run) and hit the page "http://localhost:8080/spring-fileupload-tutorial/email" nothing shows up
    c) shouldn't the correct page be "http://localhost:8080/spring-fileupload-tutorial/form" instead of "http://localhost:8080/spring-fileupload-tutorial/email"? (using form didn't work eiter)

    using ubuntu precise, with java 6 on 64 bits and google chrome

    ReplyDelete
    Replies
    1. Thanks for pointing those. I remember correcting the link before. I have checked it again and found that it still points to the wrong link (it's now linked to the correct page). I have also changed the entry page from /email to /form. Did you get any error when you tried /form?

      Delete
    2. yes, when I tried "http://localhost:8080/spring-fileupload-tutorial/form" I get a 404: The requested resource () is not available.

      Delete
    3. Wait. I checked the code. It should be http://localhost:8080/spring-fileupload-tutorial/upload

      I will correct the guide again. I got confused by your initial comment. I tested http://localhost:8080/spring-fileupload-tutorial/upload and that's the correct one.

      Delete
  2. Oh great, that worked now. Sorry for the misleading comment, and thx for looking at it

    ReplyDelete
  3. So what confused me most is the fact that by hitting the add file link, the upload service is called. Isn't that actually uploading the file?
    Then the button below says "upload", this button fires the message service.

    Very useful tutorial, thank you for this.

    ReplyDelete
    Replies
    1. Chris, I believe I had described that process in Part I under section File Upload Strategy. This is how you get thumbnails and file size reports. I believe this is also how Facebook does it and similar services (though I might be wrong)

      Delete
  4. Using IE8 I get Access denied error once I click 'Add File' and choose a file

    ReplyDelete
  5. Great tutorial but for IE7 isn't working attach a file and upload file.

    ReplyDelete
    Replies
    1. Sorry but I'm unable to test this thoroughly with IE7. I'm sure you'll have to do some workaround.

      Delete
  6. where are uploaded files hosted?

    ReplyDelete
    Replies
    1. It's in GitHub. The link is posted in Part 1 and Part 5. Here's the direct link: https://github.com/krams915/spring-fileupload-tutorial/tree/master/spring-fileupload-tutorial

      Delete
  7. Hi Krams,

    I am getting this error on page load.... (check from firebug console).

    Type Error: this.hoverable is undefined.
    this.hoverable.removeClass(...state-hover");

    -- Jquery...widget.js (line 344)

    Please mail me @ krishna@rupeelog.com

    ReplyDelete
    Replies
    1. Do you get this error on all browsers that you've tested with? Also, did you get the error from the sample project or from your own custom project?

      Delete
  8. Everything seems to be working, but I cannot find the files under the resources folder? http://localhost:8080/spring-fileupload-tutorial/resources

    Anything I'm doing wrong?

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Hi krams,

      I downloaded the source code and built the project. It seems everything is working fine but I am unable to see the uploaded files in any of the server.
      Please help me regarding this.

      Delete
    3. If you check the UploadController, you should notice the following:

      // Do custom steps here
      // i.e. Save the file to a temporary location or database
      logger.debug("Writing file to disk...done");

      It's not really being written on the disk. You have to write the code to write it which should be simple enough.

      Delete
  9. HI krams,

    is file will upload to any of the server or not? please help me on this as I am unable to see the uploaded files in any of the server.

    ReplyDelete
    Replies
    1. If you check the UploadController, you should notice the following:

      // Do custom steps here
      // i.e. Save the file to a temporary location or database
      logger.debug("Writing file to disk...done");

      It's not really being written on the disk. You have to write the code to write it which should be simple enough.

      Delete
  10. I tried to run this app with Spring 3.0.7, but I failed. Any advice?

    ReplyDelete
  11. I have read your blog its very attractive and impressive. I like it your blog.

    Spring online training Spring online training Spring Hibernate online training Spring Hibernate online training Java online training

    spring training in chennai spring hibernate training in chennai

    ReplyDelete
  12. I just saw this nice tutorial a few weeks ago. I don't consider myself a java expert programmer, so please forgive me if my question sounds naive. In upload() method of UploadController, it returns List. I'm wondering why it returns a list, when the list will contain only 1 element even if you download single or multiple file.

    Thank you.

    ReplyDelete