?
Solved

how to do file upload by only using struts action without form bean

Posted on 2005-04-04
22
Medium Priority
?
1,547 Views
Last Modified: 2008-01-09
I am trying to upload file without using a form bean, and only let the action to deal with everything. but I got exception for"no definition retrieved for form bean null", I wondering if the form bean is a must to upload a file with struts?
my html code in a test.jsp for the form :

<form action="/actions/sales/customer/test"
enctype="multipart/form-data" method="post">
<p>
Please specify the path of the logo:<br>
<input type="file" name="filename" size="40">
</p>

and the config-struts.xml is:
<action
                  path="/actions/sales/customer/test"
                  type="com.XXXXXXXX.wts.FileUploadAction"
                  input="/forms/error.jsp">
 
                 <forward name="success"              
                          path="/index.jsp"/>
                 
                 <forward name="fail"              
                          path="/forms/somewhere.jsp"/>
           
             </action>

and my action class is:
import java.io.File;
 import java.util.Iterator;
 import java.util.List;

 import org.apache.commons.fileupload.FileUpload;
 import org.apache.commons.fileupload.DiskFileUpload;
 import org.apache.commons.fileupload.FileItem;

  public class FileUploadAction extends Action
  {
        public ActionForward execute(ActionMapping mapping,
              ActionForm form,
              HttpServletRequest request,
              HttpServletResponse response) throws Exception
        {
            int sizeThresholdUploadFileMemory = 1;
            int maxUploadFileSize = 1000000;
            String COMPLETE_UPLOAD_DIRECTORY = "/";
            String tempDirectory = "/";
            boolean isMultipart;
            isMultipart = FileUpload.isMultipartContent(request);
            if (isMultipart == true)
            {
                  // Create a new file upload handler
                  DiskFileUpload upload = new DiskFileUpload();

                  // Set upload parameters
                  upload.setSizeThreshold(sizeThresholdUploadFileMemory);
                  upload.setSizeMax(maxUploadFileSize);
                  upload.setRepositoryPath(tempDirectory);

                  // Parse the request
                  // returns a list of "FileItem"
                  List items = upload.parseRequest(request);

                  // Process the uploaded items
                  Iterator iter = items.iterator();
                  while (iter.hasNext())
                  {
                        FileItem fi = (FileItem) iter.next();
                        String fieldName = fi.getFieldName();
                        boolean isFormField = fi.isFormField();
                        if (isFormField == true)
                        {
                              String value = fi.getString();
                        }  // end of IF
                        else
                        {
                              String filename = fi.getName();
                              String contentType = fi.getContentType();
                              boolean isInMemory = fi.isInMemory();
                              long sizeInBytes = fi.getSize();
                              String uploadFilename;
                              File uploadFile;
                              uploadFilename =
                                                COMPLETE_UPLOAD_DIRECTORY
                                                + filename;
                              uploadFile = new File(uploadFilename);
                              fi.write(uploadFile);
                        }  // end of ELSE
                  }  // end of WHILE
                  return(mapping.findForward("success"));
            }  // end of IF
            else
            {
                  return(mapping.findForward("fail"));
            } // end of ELSE
}//excute
}//class

can anyone help me out on this? I even can not see the jsp file for uploading. thanks.
0
Comment
Question by:arthurwang
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 6
  • 3
  • +1
22 Comments
 
LVL 4

Assisted Solution

by:orhanbaba
orhanbaba earned 200 total points
ID: 13704809
a jsp file upload example i think it will help you. i willl delete this file on sunday.
http://www.supercom.com.tr/java_arsiv/test.zip
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13705548
Have you defined your form in struts-config?

    <form-bean name="FileUploadForm" type="org.apache.struts.validator.DynaValidatorForm">
      <form-property name="file" type="org.apache.commons.fileupload.FileItem" />
    </form-bean>

Then declare your action to use the form "FileUploadForm"

That *may* work...

If not, I'll fire up Struts and have a go myself :-)

Tim
0
 
LVL 4

Expert Comment

by:orhanbaba
ID: 13705627
calm down
calm down
it just a small piece of code :))
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 35

Expert Comment

by:TimYates
ID: 13705701
?

The question is:

    "how to do file upload by only using struts action without form bean"

I was trying to show a way that might work with struts...  
0
 

Author Comment

by:arthurwang
ID: 13708027
Thank you very much for your help, orhanbaba, also, thanks for the help from TimYates,
The reason I want to use a action without formbean is the source code above I give is really a good piece source code I got from internet, it exactly follows the instruction from jakarta common fileupload project. also, I find that piece of source of code do provide a lot of control(for example, it use very concise code to save uploaded file(or files) into arbitrary directory).The above code is tested using with struts by someone, but I just don't know how to use it.  I did search internet,but did not see any source code that can upload file(or files) in such a clean way and save it into arbitrary directory. if anyone can do that with form bean used, can anyone show me your source code? thank you very much.
0
 
LVL 4

Expert Comment

by:orhanbaba
ID: 13708049
tim
i just kidding.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13708127
>> i just kidding.

Sorry, I got up late and into work late and was in a stroppy mood ;-)

Curse the snooze button! ;-)

hehehe

>> arthurwang

So that code works?  What was the question again?
0
 

Author Comment

by:arthurwang
ID: 13708204
the question is if you can have a little bit code in jsp or html to set up a submit button  on the webpage to work with this action code? this action code is tested with a java applet before for multiple image file submission together. I tried to use any general html code for file upload with this action class, but the struts told me it can not find the bean. I don't know why!
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13708308
Try putting:

    <form-bean name="FileUploadForm" type="org.apache.struts.validator.DynaValidatorForm">
    </form-bean>

in your struts-config class, then change your action tag to:

          <action
                  name="FileUploadForm"
                  path="/FileUpload"
                  type="com.XXXXXXXX.wts.FileUploadAction"
                  input="/forms/yourinputjsp.jsp">
 
Then, change "yourinputjsp.jsp" (or whatever you've called the jsp with the form on it) to:

    <form action="/FileUpload" enctype="multipart/form-data" method="post">
        <p>
          Please specify the path of the logo:<br>
          <input type="file" name="filename" size="40">
        </p>
        <input type="submit">
    </form>
0
 

Author Comment

by:arthurwang
ID: 13708504
thanks, TimYate, I copy your code and do exactly as the same as you do, but I got exception as below:

root cause

javax.servlet.jsp.JspException: Cannot find bean FileUploadFormBean in any scope
      org.apache.struts.taglib.TagUtils.lookup(TagUtils.java:992)
      org.apache.struts.taglib.html.BaseFieldTag.renderInputElement(BaseFieldTag.java:153)
      org.apache.struts.taglib.html.BaseFieldTag.doStartTag(BaseFieldTag.java:96)
      org.apache.jsp.forms.login_jsp._jspx_meth_html_file_0(org.apache.jsp.forms.login_jsp:155)
      org.apache.jsp.forms.login_jsp._jspx_meth_html_form_0(org.apache.jsp.forms.login_jsp:126)
      org.apache.jsp.forms.login_jsp._jspService(org.apache.jsp.forms.login_jsp:79)
      org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
      org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
      org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
      org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
      org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:75)

what would be the problem? thanks again.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13708540
Try:

    <form-bean name="FileUploadFormBean" type="org.apache.struts.validator.DynaValidatorForm">
    </form-bean>

That might do it...  it should make struts create a form bean (internally) with no properties...then you can just read the data off the request...

Actually writing an ActionForm with a file property is what I'm trying to avoid ;-)  But it *may* be necessary :-/
0
 

Author Comment

by:arthurwang
ID: 13709118
Again, I notice that you might lost the / at the end of the form bean statement:
<form-bean name="FileUploadFormBean" type="org.apache.struts.validator.DynaValidatorForm">

before I correct this, I got error like:
javax.servlet.jsp.JspException: Cannot find bean FileUploadFormBean in any scope
      org.apache.struts.taglib.TagUtils.lookup(TagUtils.java:992)
      org.apache.struts.taglib.html.BaseFieldTag.renderInputElement(BaseFieldTag.java:153)
      org.apache.struts.taglib.html.BaseFieldTag.doStartTag(BaseFieldTag.java:96)
      org.apache.jsp.forms.login_jsp._jspx_meth_html_file_0(org.apache.jsp.forms.login_jsp:155)
      org.apache.jsp.forms.login_jsp._jspx_meth_html_form_0(org.apache.jsp.forms.login_jsp:126)
      org.apache.jsp.forms.login_jsp._jspService(org.apache.jsp.forms.login_jsp:79)
      org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
      org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
      org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
      org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
      org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:75)


after correct it by adding one "/" there, the container can not depoy it.
0
 

Author Comment

by:arthurwang
ID: 13710707
Sorry, TimYate, i made mistakes, you code is right, you did not lost anything, but I still have the exception like below:
javax.servlet.ServletException: No getter method for property file of bean FileUploadFormBean
      org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:846)
      org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:779)
      org.apache.jsp.forms.login_jsp._jspService(org.apache.jsp.forms.login_jsp:103)
      org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
      org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
      org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
      org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
      org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:75)
0
 

Author Comment

by:arthurwang
ID: 13710785
Please, everybody help, I can not work this out.
0
 
LVL 35

Assisted Solution

by:TimYates
TimYates earned 200 total points
ID: 13714743
Ok then, as I first suggested, try:

    <form-bean name="FileUploadFormBean" type="org.apache.struts.validator.DynaValidatorForm">
        <form-property name="file" type="org.apache.commons.fileupload.FileItem" />
    </form-bean>
0
 

Author Comment

by:arthurwang
ID: 13754660
I still get the exception below:

org.apache.commons.beanutils.ConversionException: Cannot assign value of type 'org.apache.struts.upload.CommonsMultipartRequestHandler$CommonsFormFile' to property 'file' of type 'org.apache.commons.fileupload.FileItem'
      org.apache.struts.action.DynaActionForm.set(DynaActionForm.java:424)
      org.apache.commons.beanutils.PropertyUtils.setSimpleProperty(PropertyUtils.java:1769)
      org.apache.commons.beanutils.PropertyUtils.setNestedProperty(PropertyUtils.java:1684)
      org.apache.commons.beanutils.PropertyUtils.setProperty(PropertyUtils.java:1713)
      org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:1019)
      org.apache.commons.beanutils.BeanUtils.populate(BeanUtils.java:808)
      org.apache.struts.util.RequestUtils.populate(RequestUtils.java:495)

Looks like I can not work this out  by myself. TimYates, Can you try some test project on your own machine if you have time? thanks.
0
 

Author Comment

by:arthurwang
ID: 13782419
I wasted too much time on this, I got to move forward, now I only want to
1: upload a file and
2:  save it in hard disk
3: by using struts
4: either with or without formBean
5: no .jsp in address bar

thanks for every hint, comment, piece of code.



0
 
LVL 15

Accepted Solution

by:
aozarov earned 1600 total points
ID: 13783519
See struts examples (have a file upload example)

Basically doing this:

// configuration in struts-config.xml
    <form-bean name="UploadForm" type="com.XXXXXXXX.wts.UploadForm" />

     <action name="UploadForm" path="/actions/sales/customer/test" type="com.XXXXXXXX.wts.FileUploadAction" input="/forms/error.jsp">
                 <forward name="success"     path="/index.jsp"/>                
                 <forward name="fail"    path="/forms/somewhere.jsp"/>
     </action>

// Adding this code
// Form definition
package com.XXXXXXXX.wts.UploadForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

public class UploadForm extends ActionForm {
  protected FormFile myFile;

  public void setFile(FormFile file) {
    myFile = file;
  }
  public FormFile getFile() {
    return myFile;
  }
}


// Action
public class FileUploadAction extends Action
  {
       public ActionForward execute(ActionMapping mapping,
              ActionForm form,
              HttpServletRequest request,
              HttpServletResponse response) throws Exception
       {
               UploadForm uploadForm = (UploadForm) form;
               FormFile formFile = uploadForm.getFile();
               // using the FormFile API http://struts.apache.org/api/org/apache/struts/upload/FormFile.html
              String fileName = formFile.getFileName(); // get file name
              InputStream input = formFile.getInputStream(); // get the inputStream
              FileOutputStream output = new FileOutputStream("the_place_you_want_to_save");
              byte bytes[] = new byte[1024];
              int length = 0
              while ((length = input.read(bytes)) > 0)
                    output.write(bytes, 0, length);
              output.close();
            .....



// HTML
<form action="/actions/sales/customer/test"
enctype="multipart/form-data" method="post">
<p>
Please specify the path of the logo:<br>
<input type="file" name="file" size="40">
</p>
</form>
0
 

Author Comment

by:arthurwang
ID: 13785476
Hi, Aozarov, thank you very much for your answer, it really help me out, I wish I could look at the struts examples earlier. I am supposed to give all the points to you, since orhanbaba and TimYates also helped to give some solutions to let me try out. I split some points to them, if you think this is not fare, I would like to give full points to you from other sources.

Again, I really appreciate your help.
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13785573
It is definetly fine by me ;-)
Can't speak for TimYates and orhanbaba though.
0
 

Author Comment

by:arthurwang
ID: 13917996
hi, aozarov,
I just don't know how to contact you other than post here, I got a small question here:

http://www.experts-exchange.com/Programming/Q_21410831.html

I believe you may be able to help me out, thanks.

0
 

Author Comment

by:arthurwang
ID: 14702918
can anybody look at my this question, I guess maybe some of you guys can help me out.

http://www.experts-exchange.com/Web/Application_Servers/Q_21531664.html

thanks.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We live in a world of interfaces like the one in the title picture. VBA also allows to use interfaces which offers a lot of possibilities. This article describes how to use interfaces in VBA and how to work around their bugs.
In this article, WatchGuard's Director of Security Strategy and Research Teri Radichel, takes a look at insider threats, the risk they can pose to your organization, and the best ways to defend against them.
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

719 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question