Struts 2 File Upload and Save Tutorial with Example

Welcome to Part-6 of 7-part series of Struts2 Framework. In previous part we went through basics of Struts2 Interceptors. Also we created a custom interceptor and integrated it through Struts2 application. It is strongly recommended to go through previous articles in case you new to Struts2 Framework. [sc:Struts2_Tutorials] Today we will see how to do File Upload in Struts2. We will use Struts2 built-in FileUploadInterceptor in our example to upload the file. The Struts 2 File Upload Interceptor is based on MultiPartRequestWrapper, which is automatically applied to the request if it contains the file element.

Required JAR file

Before we start, we need to make sure commons-io.jar file is present in the classpath. Following are the list of required Jar files. struts2-file-upload-jar-files

Getting Started

In order to add file upload functionality we will add an action class FileUploadAction to our project. Create file FileUploadAction.java in package net.viralpatel.struts2. FileUploadAction.java
package net.viralpatel.struts2; import java.io.File; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionSupport; public class FileUploadAction extends ActionSupport implements ServletRequestAware { private File userImage; private String userImageContentType; private String userImageFileName; private HttpServletRequest servletRequest; public String execute() { try { String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”); System.out.println("Server path:" + filePath); File fileToCreate = new File(filePath, this.userImageFileName); FileUtils.copyFile(this.userImage, fileToCreate); } catch (Exception e) { e.printStackTrace(); addActionError(e.getMessage()); return INPUT; } return SUCCESS; } public File getUserImage() { return userImage; } public void setUserImage(File userImage) { this.userImage = userImage; } public String getUserImageContentType() { return userImageContentType; } public void setUserImageContentType(String userImageContentType) { this.userImageContentType = userImageContentType; } public String getUserImageFileName() { return userImageFileName; } public void setUserImageFileName(String userImageFileName) { this.userImageFileName = userImageFileName; } @Override public void setServletRequest(HttpServletRequest servletRequest) { this.servletRequest = servletRequest; } }
Code language: Java (java)
In above class file we have declared few attributes:
  • private File userImage; -> This will store actual uploaded File
  • private String userImageContentType; -> This string will contain the Content Type of uploaded file.
  • private String userImageFileName; -> This string will contain the file name of uploaded file.
The fields userImageContentType and userImageFileName are optional. If setter method of these fields are provided, struts2 will set the data. This is just to get some extra information of uploaded file. Also follow the naming standard if you providing the content type and file name string. The name should be ContentType and FileName. For example if the file attribute in action file is private File uploadedFile, the content type will be uploadedFileContentType and file name uploadedFileFileName. Also note in above action class, we have implemented interface org.apache.struts2.interceptor.ServletRequestAware. This is to get servletRequest object. We are using this path to save the uploaded file in execute() method. We have used FileUtil.copyFile() method of commons-io package to copy the uploaded file in root folder. This file will be retrieved in JSP page and displayed to user.

The JSPs

Create two JSP file in WebContent folder. UserImage.jsp will display a form to user to upload image. On submit, the file will be uploaded and saved on server. User will be sent to SuccessUserImage.jsp file where File details will be displayed. Copy following code into it. UserImage.jsp
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Upload User Image</title> </head> <body> <h2>Struts2 File Upload & Save Example</h2> <s:actionerror /> <s:form action="userImage" method="post" enctype="multipart/form-data"> <s:file name="userImage" label="User Image" /> <s:submit value="Upload" align="center" /> </s:form> </body> </html>
Code language: HTML, XML (xml)
SuccessUserImage.jsp
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Success: Upload User Image</title> </head> <body> <h2>Struts2 File Upload Example</h2> User Image: <s:property value="userImage"/> <br/> Content Type: <s:property value="userImageContentType"/> <br/> File Name: <s:property value="userImageFileName"/> <br/> Uploaded Image: <br/> <img src="<s:property value="userImageFileName"/>"/> </body> </html>
Code language: HTML, XML (xml)

Struts.xml entry

Add following entry for FileUploadAction class to struts.xml file.
<action name="userImage" class="net.viralpatel.struts2.FileUploadAction"> <interceptor-ref name="fileUpload"> <param name="maximumSize">2097152</param> <param name="allowedTypes"> image/png,image/gif,image/jpeg,image/pjpeg </param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> <result name="success">SuccessUserImage.jsp</result> <result name="input">UserImage.jsp</result> </action>
Code language: HTML, XML (xml)
Note that in above entry we have specified two parameter to fileUpload interceptor, maximumSize and allowedTypes. These are optional parameters that we can specify to interceptor. The maximumSize param will set the maximum file size that can be uploaded. By default this is 2MB. And the allowedTypes param specify the allowed content types of file which can be uploaded. Here we have specified it to be an image file (image/png,image/gif,image/jpeg,image/pjpeg). The file upload interceptor also does the validation and adds errors, these error messages are stored in the struts-messsages.properties file. The values of the messages can be overridden by providing the text for the following keys:
  • struts.messages.error.uploading – error when uploading of file fails
  • struts.messages.error.file.too.large – error occurs when file size is large
  • struts.messages.error.content.type.not.allowed – when the content type is not allowed

That’s All Folks

Compile and Execute the project in eclipse and goto link http://localhost:8080/StrutsHelloWorld/UserImage.jsp Image Upload Screen struts2-file-upload-example Image Upload Screen in case of error struts2-file-upload-error Image Upload Screen on success struts2-file-upload-success

Download Source Code

Click here to download Source Code without JAR files (20KB)

Moving On

Struts2 makes life very easy. It was like a piece of cake to implement File Upload with Struts2. In next part we will see Struts2 Ajax Example.
Get our Articles via Email. Enter your email address.

You may also like...

93 Comments

  1. jawahar says:

    hi viral one help can you autocompleter example in Struts2

  2. jawahar says:

    hi viral one help can you post autocompleter example in Struts2

  3. Zubin says:

    I am new to struts 2.This is really a very good example….It helped me a lot….Thanks….
    Question : How to store the File in the database(Like Oracle) ??? Can you please provide the code for it???
    Thanks in advance….

  4. finosh says:

    I am thankful to viral for help me in struts2

  5. Arscek says:

    Hello! Thanks for this tutorial, it was very helpful. I have one problem. When my form is loaded, it needs some dynamic data to be loaded from my DB(some selects, and labels). It works great if I don’t upload wrong file types, but when I try to upload a different kind of file, it doesn’t load the dynamic data. If I redirect to the action, it works fine, but then it doesn’t show the error message, this is my struts.xml, as you can see, it uses wildcards to handle method invocation:

    newTicket.jsp
    /WEB-INF/HelpDeskForms/segResponder.jsp
    /WEB-INF/HelpDeskForms/segRequester.jsp
    /WEB-INF/HelpDeskForms/segAdmSup.jsp
    /WEB-INF/HelpDeskForms/newTicket.jsp
    /WEB-INF/HelpDeskForms/detRequester.jsp
    unassignedByAreaTicket
    postCreateTicket

    ………..

  6. jay says:

    Hi,,, Thanks for the article….
    But im not getting output… It says…
    userImageFileName is null
    and giving NullpointerException
    Any extra code to write than you have given above..
    I think no but wat is the reason why its giving NullPointerException…….?
    Plz… Thanks in advance….

  7. jay says:

    System.out.println(“user Image :” + userImage);
    System.out.println(“user Image Name:” + userImageFileName);

    Both are returning null so

    File fileToCreate = new File(filePath, getUserImageFileName());
    returning NullPointerException

    any help plz….

    • Gopikrishnan says:

      Hi,
      The error you have faced – “I have problem with String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”); .It allways return null .And I get a java.lang.NullPointerException
      plz I need your help”
      can be resolved by adding the following interceptor in your struts.xml since the file upload action you are calling doesnt call the servlet class at that instance.

      Interceptor:

      example below is the one used in my application

      application/vnd.ms-excel
      <!– 10240 10KB –>
      2097152

      fileUpload.def
      Footer.jsp

  8. mistersimpatiko says:

    try to remove the interceptors, this works for me. but its weird… :)

  9. swag01 says:

    I am really enjoying this tutorial!!! Great job.

    Everything is working for me using jboss; however, I noticed that servletRequest.getRealPath…

    is coming up with a deprecation message.

    What is the replacement for this?

    Thanks again!

    • @swag01: Thanks for pointing out this. ServletRequest.getRealPath() method has been deprecated as the same method is available in javax.servlet.ServletContext interface.

  10. swag01 says:

    Thanks Viral;

    I made the corrections to the FileUploadAction.java (It didn’t like the @override so I commented that out too):

    If you want to update your code with the changes, I am fine.

    //src

    • @swag01 – Thanks for the source code. I have updated the above java code and removed call to deprecated method.

  11. dWang says:

    Thanks Viral;
    Where is the uploded image file?
    The tmp file is not there any more as shown on SuccessUserImage.jsp:
    User Image: D:\share\workspaceStruts2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Struts2HelloWorld\upload_4fc01309_12a30f1701e__8000_00000011.tmp
    Thanks again!
    dWang

  12. vin says:

    thanks a lot mr.viral patel.
    ur tutorial helped well to learn struts2.0.

  13. Naks says:

    ur struts.xml file donot works.
    plz kindly send some guide line

  14. Larry says:

    For the ServletRequest.getRealPath() deprecation I resolved with:

    servlet-api.jar
    and
    String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”);

  15. ali says:

    hi.
    i have a problem with changing displayed message.
    my mean is when i override the messages when file size is over than my specified size like as below :
    struts.messages.error.file.too.large=Uploaded file was too large.
    in my two file
    ApplicationResource.properties , ApplicationResource_fr.properties
    only english or default message be displayed and if changing my locale it has not any effect.

  16. swathi says:

    hi im new to struts2.i have to write validation for file upload field.can any one help me

  17. swathi says:

    hi im new to struts2.i have to write validation for file upload field.can any one help me………………

  18. swathi says:

    hi

  19. workingforjava says:

    Swathi,

    please refere the previous post (Struts2 Validation Framework Tutorial with Example
    )..if u dont just reply i will give you the code.

    Regards,
    [email protected]

  20. Bhavik says:

    i am impressed in the first visit.
    hope it will solve all my problem related asynchronously file upload.

  21. Chooyoon Kim says:

    At last I can solve the question and errors using your valuable Tiles Example after 4 hours st\ruggle against the incomplete articles and codes posted to Korean Websites by my people. Thank you! Pls post the more examples….. .

  22. shiva says:

    any one help how to attach file and store that file in database with example

  23. adbeng says:

    I have problem with String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”); .It allways return null .And I get a java.lang.NullPointerException
    plz I need your help

  24. kannan says:

    Yes, I also have that same problem with String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”); .It allways return null .And I get a java.lang.NullPointerException
    plz I need your help

    • adbeng says:

      hii kannan pay attention to FileUploadAction class :you have just to copy as its write here and its work very well.Good luck .

  25. Pradeep says:

    Hi,
    Can you help to debug the following error in my eclipse deployment. I have downloaded he source code and added the binaries as mentioned here.
    I’m getting the following warning

    WARNING: No configuration found for the specified action: ‘userImage’ in namespace: ”. Form action defaulting to ‘action’ attribute’s literal value.
    Oct 14, 2011 3:14:57 PM org.apache.struts2.dispatcher.Dispatcher getSaveDir
    INFO: Unable to find ‘struts.multipart.saveDir’ property setting. Defaulting to javax.servlet.context.tempdir

    and the page gives following error

    HTTP Status 404 – /StrutsHelloWorld/userImage

    ——————————————————————————–

    type Status report

    message /StrutsHelloWorld/userImage

    description The requested resource (/StrutsHelloWorld/userImage) is not available.

  26. GV says:

    Hi Pradeep,

    For testing,In web.xml instedof Login.jsp update it to UserImage.jsp and test updaload process.

  27. ck says:

    Thanks so much Viral, with your tutorial, it help me to study struts2 very quick. Thank you very much

  28. Arun says:

    the program is working fine. but pls tell me where the file is getting uploaded in the server. pls tell me how to change the file path where i upload the file in the server. thanks in advance. you are doing a great job.

  29. Preeti says:

    Hi,viral this was a very nice tute..one help i need ,actually needs to design a dojo tree with the help of json and this json should be from action class of struts 2.can u help me out…sa soon as posible…thanks

  30. eknath says:

    Its Fine tutorial But i want to save that image to mysql database can u help me with the code

  31. harish says:

    thank u it helped me lot

  32. Gowri says:

    Hi…I got the output expect for one thing….The image is not getting displayed on the success page.Actually the upload______________ ,.tmp gets saved in that path specified but gets removed at some point of time and I can also see this msg in the console
    “INFO: Removing file userImage S:\Java J2EE\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\StrutsHelloWorld\upload__26c8c9ec_135c27471c0__8000_00000000.tmp

    So as it gets removed ,there is no image for it to display.Kindly help me…

  33. bhavesh says:

    thank this demo is really good for me

  34. Rajagopal says:

    This works only if we have

    in UserImage.jsp

  35. i want to upload a txt,doc,png,gifand jpeg file all file are upload differert operation please provide me code of that process.

  36. Ravi Saini says:

    Hi Sir, when I try to upload a image through given source i got following error help me………

    javax.servlet.ServletException: Filter execution threw an exception

    root cause

    java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
    org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:199)
    org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:361)
    org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest.parse(JakartaMultiPartRequest.java:90)
    org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper.(MultiPartRequestWrapper.java:73)
    org.apache.struts2.dispatcher.Dispatcher.wrapRequest(Dispatcher.java:698)
    org.apache.struts2.dispatcher.FilterDispatcher.prepareDispatcherAndWrapRequest(FilterDispatcher.java:334)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:394)

    root cause

    java.lang.ClassNotFoundException: org.apache.commons.io.output.DeferredFileOutputStream
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
    org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:199)
    org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:361)
    org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest.parse(JakartaMultiPartRequest.java:90)
    org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper.(MultiPartRequestWrapper.java:73)
    org.apache.struts2.dispatcher.Dispatcher.wrapRequest(Dispatcher.java:698)
    org.apache.struts2.dispatcher.FilterDispatcher.prepareDispatcherAndWrapRequest(FilterDispatcher.java:334)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:394)

    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.21 logs.

  37. hana says:

    s’il vous plait comment faire pour recuperer l’extention de l’image charger

  38. hana says:

    c bon c le champ userImageContentType qui definie l’extension

  39. Vishal says:

    Hi Viral,

    Thanks for this tutorial it helped me lot. But I want to save image in MySql DB and show it on webpage so do you have any tutorial of saving the image in BLOB format and retrieving it. I want this in struts 2 framework only…not in spring / hybernate..

    Best Regards,
    Vishal Kshirsagar.

  40. sreenu says:

    hi sir this is sreenu , iam complete in mca 2012 batch my problam is how to use multepull jsp
    using singlesite …..

  41. Gowri says:

    Hi…can somebody tell me why the image is not displayed for some reason..I see it with a cross red symbol..in my console I can an INFO: saying removed file from that path …blah…/ that long file name…whats the reason?

  42. mohit says:

    Hi….
    I have uploaded my file using struts2 interceptor in a specific folder,but problem is that the file name get saved with upload__421b43ec_138b840f6aa__7ff0_00000001.tmp
    can somebody tell me why that’s so????
    any help will be appreciated.!!!!

  43. rakesh says:

    how many jars i need for this File upload example

  44. bhanu says:

    Thank you

  45. srinu says:

    while am writting this line

    String filePath = request.getSession().getServletContext().getRealPath(“/”);

    am getting the error as illegeal charecter can any one help me

  46. g_07 says:

    Does this work? Because i don’t think it should as the:
    <img src="”/>

    is referring to which path?
    if it’s the real path then i don’t think it’s able to refer to the physical path eg. “C:\struts2\fileupload\userimage.jpg”

  47. gourav saxena says:

    hi
    its really help full, i m uesing same example but when i m uploading big image that time error msg coming two times.
    it should be one time only………..

  48. shweta says:

    Hello, I am trying to use file-upload example to upload swf file using struts2 but it is givign me 404 error. It is working for other video fiels and pdf but not for swf files…please help…

  49. Manu says:

    Can anyone please tell me how to upload multiple files using a single file tag in structs2

  50. nirav says:

    Dear,
    my entire application depends on file upload where it uses struts 2 file upload as suggested all steps are followed and it’s working fine in my local(windows) environment while it’s not working in my test(linux) environment.

    it gives null pointer exception. File object is null in action class.

    Log trace :----
    java.lang.NullPointerException at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:82) at com.fvrl.web.department.DepartmentAction.upload(DepartmentAction.java:104) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254) at com.fvrl.web.interceptors.SecurityManager.intercept(SecurityManager.java:61) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:498) at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231) at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) at java.lang.Thread.run(Thread.java:662)
    

  51. HP says:

    userImageFileName null please help me?

  52. Nagbhushan says:

    Getting big Null Pointer Exception at line:

    fileToCreate = new File(filePath, this.htmlFileName);

    However userImage value in debug mode is :

    “D:XYZ\workspace_4\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\HTMLToJSP\upload__1d70e13a_13b8a3f0bbd__8000_00000000.tmp”

  53. Sandaruwan says:

    I got that null issue all the time using glassfish 3.1.2
    I switched to tomcat server and it worked fine.
    I just changed server to glassfish 3.1.2.1 version and it also worked fine..

    I think the issue was with the server.
    Just to let u know.. Cheers..

    • bhavesh says:

      i have executed it …with the code ..
      the problem is when i execute the UserImage.jsp after giving every details
      and when i click on submit button ,then it goes to SuccessUserImage where it dosnt gives the oproper output …evry fields is empty …(NO OUTPUT)
      SOME1 plz help me,,,,,,,

  54. Kumar says:

    when I am Giving Image file It Is working, but when i am not giving any image, it is not showing error message in UserImage.jsp, But it is returning the UserImage.jsp..
    Plz tell me how to show error message in UserImage.jsp

    Thanx In Advance

  55. modtanoi says:

    where is photo after upload fie?

  56. Ahmed says:

    I am getting the filename, contentType empty, and having null exception at
    File filetocreate = new File(filepath, fileName)
    fileName value is null in the action.
    thought the filename gets uploaded and displays the file name in jsp file.

    • Ahmed says:

      Oh Just solve the filename null axception in the action.

      the solution is:

      whatever you name your file variable, let say
      privare File fileUpload;

      the ContentType and FileName should be prefixed by the “fileUpload” like below:
      private String fileUploadContentType;
      private String fileUploadFileName

      hope this will help those who are having same problem

  57. Rahul says:

    Hi Viral –
    Have one doubt , is it is possible to configure file upload maximumSize value by programatically. because I have to configure different fileupload maxSize limit for different roles ( users ).
    If yes please give some ideas.

    Is it is possible to override fileUpload interceptor .

  58. devika says:

    I want the file to be saved in the directory with a seperate file extension.Like if i uploaded a .jpeg or .gif file i want both to be saved in .jpeg format.Is it possible??How?

  59. Thanks Viral,
    Very good tutorial.

    Joe.

  60. saurabh says:

    Thank you for sharing code this work for me
    I have 1 question how to change by default the path of image upload?

  61. rasmi says:

    how can i change the path of saved file???or can i save the uploaded file into folder of my application??

  62. Sanjoy Roy says:

    When i run your above code , i get the follwoing error :

    The type UploadFile must implement the inherited abstract method ServletRequestAware.setServletRequest(HttpServletRequest

    I need ur help urgent !
    Thanks,
    Sanjoy Roy

    • Mel says:

      public class SampleStrutsAction implements ServletRequestAware{
      private HttpServletRequest request;
      
      @Override
      	public void setServletRequest(HttpServletRequest request) {
      		// TODO Auto-generated method stub
      		this.request = request;
      	}
      }
      

    • Mel says:

      public class SampleStrutsAction implements ServletRequestAware{
               private HttpServletRequest request;
      
               /**
               * You need to declare this method when implementing ServletRequestAware
               */
              @Override
      	public void setServletRequest(HttpServletRequest request) {
      		// TODO Auto-generated method stub
      		this.request = request;
      	}
      }
      

  63. Latifa says:

    thanks for this tutoriel, how can i adapt the code in order to upload other file (pdf,txt,…)?

  64. lakhan says:

    hi.its very helpful tutorial…Thanks Viral….

  65. calin says:

    was is such a big deal to upload those da*n JARs ?
    not working for me

  66. Balram says:

    @Viral : thanks for great tutorials …
    please also update source code which has been given for download.

  67. anu says:

    thanx for this tutorial and please give tutorials for downloading a file.

  68. Vikrant deshmukh says:

    Sir, is it possible to upload video or audio file using this ???
    what i need to do this ?please help me its urgent

    Regards
    vikrant Deshmukh

  69. Sivaji A says:

    Please help if the file size is larger.
    I am getting no action defined error.

  70. prashanth says:

    Hi everyone,
    Can anyone tell me how to fix “content type not allowed” error.

  71. ranjeet says:

    sir plz tell me where to get the jar files in tiles project

  72. swapna says:

    Hi ,

    If I use some other names like filepath and copied file instead of userImage and userImageFileName then why my program is not working.Do there is any connection with the names in the action class and the interceptors.I have used the same names in the jsps also.

  73. Ravi says:

    hi sir .
    String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”);

    here i want to save location in my project files how can i set this path
    i want “WebContent/” like This
    And
    i don’t want to this type of locations “E:/myphotos/”

    thanks

    • skr says:

      did u solve this problem as i want same thing to do in my project

  74. Arpit says:

    good tutorial

  75. Nans says:

    Hi,

    Am getting images from the database and storing all the images in a filepath( request.getSession().getServletContext().getRealPath). Now am having all the images in the filepath.

    Then am getting the images from filepath to

    private File[] filelist;

    Now am trying to display the filelist in JSP:

    <img src="”/>

    Output in browser is am getting the filepath of all the images(i can iterate) but images are not loading.

    If i put the tag in and click on the link its displaying “The address wasn’t understood”.If i enter the link the slash “/” is changing and the image in displaying.

    <a href="”/>
    <img src="”/>

    In Firebug its showing “Could not load image”.

    I may be wrong in displaying the image so please help how to load the image in JSP.

  76. Nans says:

    s iterator property is not displaying in the comment..
    actually am iteration using filelist[] where am having all the images from the filepath.And using s propery am trying to display the image.

  77. MM says:

    Thanks a lot for the great tutorials.
    I have created a FileUpload function. Everything is working fine locally. I have uploaded on production. The interceptor intercepting the docx file.

    Following is the code in struts.xml

    104857600
    text/plain,application/vnd.openxmlformats-officedocument.wordprocessingml.document


    I will appreciate any advise.

  78. Binh Thanh Nguyen says:

    Thanks, nice post

  79. Ganga says:

    Good example…..thanks to the author..Keep up the great work u’re doing!

  80. skr says:

    how can i store image in web project folder like project name/webcontent/upload

  81. Sathish says:

    I tried the code for file upload but it replies
    “java.lang.NullPointerException”

    How to solve this?

  82. anant vishwakarma says:

    Very Nice and thanks for share to a useful this post

  83. Ravi Kant Sharma says:

    I upload my image successfully
    Thanks for share

Leave a Reply

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