• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1685
  • Last Modified:

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

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
arthurwang
Asked:
arthurwang
  • 11
  • 6
  • 3
  • +1
3 Solutions
 
orhanbabaCommented:
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
 
TimYatesCommented:
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
 
orhanbabaCommented:
calm down
calm down
it just a small piece of code :))
0
Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

 
TimYatesCommented:
?

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
 
arthurwangAuthor Commented:
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
 
orhanbabaCommented:
tim
i just kidding.
0
 
TimYatesCommented:
>> 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
 
arthurwangAuthor Commented:
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
 
TimYatesCommented:
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
 
arthurwangAuthor Commented:
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
 
TimYatesCommented:
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
 
arthurwangAuthor Commented:
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
 
arthurwangAuthor Commented:
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
 
arthurwangAuthor Commented:
Please, everybody help, I can not work this out.
0
 
TimYatesCommented:
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
 
arthurwangAuthor Commented:
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
 
arthurwangAuthor Commented:
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
 
aozarovCommented:
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
 
arthurwangAuthor Commented:
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
 
aozarovCommented:
It is definetly fine by me ;-)
Can't speak for TimYates and orhanbaba though.
0
 
arthurwangAuthor Commented:
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
 
arthurwangAuthor Commented:
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

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 11
  • 6
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now