0 Replies Latest reply: Oct 2, 2007 7:04 AM by 807574 RSS

    File Upload Problem

    807574
      I have posted this querry in the JSF topic. But posting is here too.

      I want to upload a file from the front end using JSF and Portlets deployed on IBM WebSphere Portal.

      I have used Apache's commons file upload functionality as the file upload provided in JSF doesnot work with portlets and the action event is not invoked If I keep enctype="multipart/form-data". So I included 3 forms in my Faces JSP file.
      1) h:form = For displyign error message on screen
      2) html:form = Include the enctype="multipart/form-data" and the input type file for uploading. And a submit button
      3) h:form: Here I have a command link which is remotely excuted on click of sumit button in my html form. This is to invoke the action event in the pagecode to get the bean value from the context.

      Now in the my doView method in the portlet, isMultipartContent(httpservletrequest) always returns false as the content type is text/html and not multipart. Onclick of the submit button in the the html form I am calling a javascript function which sets the __LINK_TARGET__ to the command link in the 3rd h:form which will call the page code.
      The problem here is action is invoked only when I return false from the above javascript else it will trigger for the first time and from second time onwards it will not invoke the action event in the pagecode method. Whent the javascript function returns false, the content type is always text/html. However if I return "true" from the javascript the content type is multipart/form-data, but the action is not triggered for the second time. So basically when the javascript functions returns true, for the first click everything works perfectly. When it returns false, the content type is text/html, but the action is invoked in the page code every time.

      Returning always true would solve my problem with the content type, but the action with the command link will not get invoked always as its some type of problem with h:commanLink :(.

      I guess I gave too much info. Heres my code stepby step.
      1:
      ======================= Faces JSP File: BPSMacro.jsp ====================

      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <meta name="GENERATOR" content="IBM Software Development Platform">
      <meta http-equiv="Content-Style-Type" content="text/css">
      <%@taglib uri="http://java.sun.com/portlet" prefix="portlet"%>
      <%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
      <%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>
      <%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
      <%@taglib uri="http://www.ibm.com/jsf/html_extended" prefix="hx"%>
      <%@taglib uri="/WEB-INF/tld/j4j.tld" prefix="j4j"%>
      <%@taglib uri="/WEB-INF/tld/core.tld" prefix="core"%>
      <%@page language="java" contentType="text/html; charset=ISO-8859-1"
           pageEncoding="ISO-8859-1" session="false"%>
      <portlet:defineObjects />
      <link rel="stylesheet" type="text/css"
           href='<%= renderResponse.encodeURL(renderRequest.getContextPath() + "/theme/stylesheet.css") %>'
           title="Style">

      <script type="text/javascript">
      function formSubmit() {
           var formName2 = document.getElementById("proxy_form_main_").title;
           var formName1 = document.getElementById("BPSMacroFormId").title;
           document.getElementById("__LINK_TARGET__").value = document.getElementById("proxy_HD_COMMAND_").title;
           document.getElementById(formName2).submit();
           return false;
      }

      </script>

      <f:view>
           <hx:scriptCollector id="bpsMacroScriptCollector">
                <f:loadBundle var="bps" basename="bordereauprocessingsystem" />
                <table bgcolor="#FFF9C3">
                     <tr>
                          <td><h:form id="BPSMacroFormMain" styleClass="form">
                               <table class="tablemiddle" cellspacing="0" cellpadding="0">
                                    <tr>
                                         <td><h:messages layout="table" styleClass="errormessage"
                                                   id="ValidationErrorMsg" /> </td>
                                    </tr>
                               </table>
                               <j4j:idProxy id="proxy_form_main_0_" />
                          </h:form></td>
                     </tr>
                     <tr>
                          <td>
                          <form id="BPSMacroFormId" enctype="multipart/form-data">
                          <table bgcolor="#FFF9C3">
                               <tr>
                                    <td height="36" width="324">Worksheet <input type="file"
                                         name="upfile" /></td>
                               </tr>
                                    <tr>
                                         <td align="center" width="324"><input TYPE="submit"
                                         onclick="return formSubmit();" value="Upload">
                                    </td>
                               
                               </tr>
                          </table>
                          </form>
                          </td>
                     </tr>
                     <tr>
                          
                          <td>
                          
                          <h:form id="BPSMacroFormMain2" styleClass="form">
                               <table cellspacing="2" cellpadding="2" class="tablemiddle">
                                    <tbody>
                                         <tr>
                                              <td colspan="2" align="center"><h:commandLink
                                                   styleClass="commandLink" id="lnkuserdelete"
                                                   action="#{pc_BPSMacro.doIdUpload1Action}">
                                                   <hx:graphicImageEx
                                                        styleClass="graphicImageEx" id="imgBtnCreateUser"
                                                        value="/theme/images/btnUpload.gif" style="border:0;cursor:pointer"></hx:graphicImageEx>
                                                   <j4j:idProxy id="proxy_HD_COMMAND_" />
                                              </h:commandLink></td>
                                              <h:inputHidden id="dtSize"
                                                   value="#{pc_BPSMacro.fileDetailsList.clicked}">
                                                   <j4j:idProxy id="proxy_clicked_" />
                                              </h:inputHidden>
                                              
                                         </tr>
                                         
                                    </tbody>
                               </table>
                               
                               <j4j:idProxy id="proxy_form_main_" />
                          </h:form>
                          
                     </td>
                     </tr>
                </table>
           </hx:scriptCollector>
      </f:view>
      ================== END: FACES JSP FILE: BPSMacro.jsp ========================
      2:
      =================== Action event in the Page Code: BPSMacro.java ============
      public String doIdUpload1Action() {
                System.out.println("PageCode");
                FacesContext context = FacesContext.getCurrentInstance();
                BPSMacroDetailsDataBean fileDetails = (BPSMacroDetailsDataBean)context.getApplication().createValueBinding("#{fileDetails}").getValue(context);
                BPSMacroListDataBean fileDetailsList = (BPSMacroListDataBean)context.getApplication().createValueBinding("#{fileDetailsList}").getValue(context);
                PortletSession sess = (PortletSession)context.getExternalContext().getSession(false);
                sess.setAttribute("BPS_MACRO_CONTEXT", context, PortletSession.APPLICATION_SCOPE);
                sess.setAttribute("BPS_MACRO_FILE_DETAILS", fileDetails, PortletSession.APPLICATION_SCOPE);
                sess.setAttribute("BPS_MACRO_FILE_LIST", fileDetailsList, PortletSession.APPLICATION_SCOPE);
                
                HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                request.getContentType();
                
                return "gotoBPSMacro";
      }

      ============== END Of Page Code Action event ==============================

      3:
      ============== doView() Portlet method ================================
      public void doView(RenderRequest arg0, RenderResponse arg1)
           throws PortletException, IOException {
                String METHOD_NAME = "doView(RenderRequest arg0, RenderResponse arg1)";
                Logger.debug(this.getClass(), METHOD_NAME, "Entering BPSMacroPortlet");
                
                FacesContext context = FacesContext.getCurrentInstance();      
                PortletSession sess1 = arg0.getPortletSession(true);
                BPSMacroDetailsDataBean fileDetails = new BPSMacroDetailsDataBean();
                BPSMacroListDataBean fileDetailsList = new BPSMacroListDataBean();
                context = (FacesContext)sess1.getAttribute("BPS_MACRO_CONTEXT", PortletSession.APPLICATION_SCOPE);
                if(context != null){
                     fileDetails = (BPSMacroDetailsDataBean)sess1.getAttribute("BPS_MACRO_FILE_DETAILS", PortletSession.APPLICATION_SCOPE);
                     fileDetailsList = (BPSMacroListDataBean)sess1.getAttribute("BPS_MACRO_FILE_LIST", PortletSession.APPLICATION_SCOPE);
                }
                sess1.removeAttribute("BPS_MACRO_CONTEXT", PortletSession.APPLICATION_SCOPE);
                sess1.removeAttribute("BPS_MACRO_FILE_DETAILS", PortletSession.APPLICATION_SCOPE);
                sess1.removeAttribute("BPS_MACRO_FILE_LIST", PortletSession.APPLICATION_SCOPE);
                HttpServletRequest servletRequest = (HttpServletRequest)arg0;
                PortletRequest pReq = (PortletRequest)arg0;
                HttpServletResponse servletResponse= (HttpServletResponse)arg1;
                
                System.out.println("\n\n Content Type" + servletRequest.getContentType());
           
                try{
                     if(context != null){
                     
                     
                boolean isFileMultipart = ServletFileUpload.isMultipartContent(servletRequest);

                System.out.println("\nFILE TO BE UPLOADED IS MULTIPART ? " + isFileMultipart);
                
                if(isFileMultipart){
                
                     FileItemFactory factory = new DiskFileItemFactory();
                     ServletFileUpload upload = new ServletFileUpload(factory);
                                    
                     List items = upload.parseRequest(servletRequest);
                     Iterator iterator = items.iterator();
                               
                     while (iterator.hasNext()) {
                          
                          FileItem item = (FileItem) iterator.next();
                     
                          InputStream iStream = item.getInputStream();
                          ByteArrayOutputStream ByteArrayOS = new ByteArrayOutputStream();
                          int sizeofFile =(int) item.getSize();
                          byte buffer[] = new byte[sizeofFile];
                          int bytesRead = 0;
                     
                          while( (bytesRead = iStream.read(buffer, 0, sizeofFile)) != -1 )
                          {
                               ByteArrayOS.write( buffer, 0, bytesRead );
                          }
                     
                          String data = new String( ByteArrayOS.toByteArray() );
                          int k = 0;
                          
                          //Check if the file is Refund or Premium
                          int dynamicArraySize = 0;// = st2.countTokens() * 9;
                          dynamicArraySize = st2.countTokens() * 9;
                          

                          if (!item.isFormField() ){
                               
                          
                               File cfile=new File(item.getName());
                               String fileName = "";
                               String separator = "\\";
                               int pos = item.getName().lastIndexOf(separator);
                               int pos2 = item.getName().lastIndexOf(".");

                               if(pos2>-1){
                                    fileName =item.getName().substring(pos+1, pos2);
                               }else{
                                    fileName =item.getName().substring(pos+1);
                               }
                                                                                 
                               File fileToBeUploaded=new File("C:\\Sal\\BPS MACRO\\FileTransfer\\Desti", fileName);
                               
                               item.write(fileToBeUploaded);
                               validate.displaySuccessMessage(context);
                     }
           
                }
           
                }catch(Exception e){System.out.println(e);
                     
                }
                
                Logger.debug(this.getClass(), METHOD_NAME, "Leaving BPSMacroPortlet");
                super.doView(arg0, arg1);
           }

      ==== END: doView method in the portle class. ================================