8 Replies Latest reply on Jul 23, 2010 1:03 AM by Mohtisham Anwar

    rich:fileupload with request scope?

    Mohtisham Anwar Newbie

      How we can upload files with backing beans having the request scope. It is working fine with the session scope. But when i change the scope from session to request it stops showing the picture im using the following code.

       

      <?xml version='1.0' encoding='UTF-8' ?>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:ui="http://java.sun.com/jsf/facelets"
          xmlns:f="http://java.sun.com/jsf/core"
          xmlns:h="http://java.sun.com/jsf/html"
          xmlns:a4j="http://richfaces.org/a4j"
          xmlns:rich="http://richfaces.org/rich"
          xmlns:t="http://myfaces.apache.org/tomahawk">

       


      <ui:composition template="layout.xhtml">
          <ui:define name="title">Picture Upload</ui:define>
          <ui:define name="content">
              <f:view>
                  <rich:panel>
                      <f:facet name="header">
                          <h:outputText value="Picture Upload" />
                      </f:facet>

       

                      <h:form id="uploadPic">
                          <h:panelGrid columns="2" id="user">
                          <h:outputText value="User Name" />
                          <h:inputText value="#{fileUploadBean.userName}" id="userName"/>                   
                          </h:panelGrid>
                         
                          <h:panelGrid columns="2" columnClasses="top,top">
                              <rich:fileUpload fileUploadListener="#{fileUploadBean.listener}"
                                  maxFilesQuantity="#{fileUploadBean.uploadsAvailable}" id="upload"
                                  immediateUpload="false"
                                  acceptedTypes="jpg, jpeg, gif, png, bmp"
                                  allowFlash="true"  >
                                  <a4j:support event="onuploadcomplete" reRender="info" process="uploadPic"/>
                              </rich:fileUpload>
                              <h:panelGroup id="info">
                                  <rich:panel bodyClass="info">
                                      <f:facet name="header">
                                          <h:outputText value="Uploaded Files Info" />
                                      </f:facet>
                                      <h:outputText value="No files currently uploaded"
                                          rendered="#{fileUploadBean.size==0}" />
                                      <rich:dataGrid columns="1" value="#{fileUploadBean.files}"
                                          var="file" rowKeyVar="row">
                                          <rich:panel bodyClass="rich-laguna-panel-no-header">
                                              <h:panelGrid columns="2">
                                                  <a4j:mediaOutput element="img" mimeType="#{file.mime}"
                                                      createContent="#{fileUploadBean.paint}" value="#{row}"
                                                      style="width:100px; height:100px;" cacheable="true">
                                                      <f:param value="#{fileUploadBean.timeStamp}" name="time" />
                                                  </a4j:mediaOutput>
                                                  <h:panelGrid columns="2">
                                                      <h:outputText value="User Name:" />
                                                      <h:outputText value="#{fileUploadBean.userName}" />
                                                      <h:outputText value="File Name:" />
                                                      <h:outputText value="#{file.name}" />
                                                      <h:outputText value="File Length(bytes):" />
                                                      <h:outputText value="#{file.length}" />
                                                  </h:panelGrid>
                                              </h:panelGrid>
                                          </rich:panel>
                                      </rich:dataGrid>
                                  </rich:panel>
                                  <rich:spacer height="3" />
                                  <br />
                                  <a4j:commandButton action="#{fileUploadBean.clearUploadData}"
                                      reRender="info, upload" value="Clear Uploaded Data"
                                      rendered="#{fileUploadBean.size>0}" />
                              </h:panelGroup>
                          </h:panelGrid>
                      </h:form>

       

                  </rich:panel>
              </f:view>
          </ui:define>
      </ui:composition>
      </html>

       

      package backingBeans;

       


      import java.io.IOException;
      import java.io.OutputStream;
      import java.util.ArrayList;

       

      import org.richfaces.event.UploadEvent;
      import org.richfaces.model.UploadItem;
      import org.springframework.context.annotation.Scope;
      import org.springframework.stereotype.Component;

       

      /**
      * @author Ilya Shaikovsky
      *
      */
      @Component("fileUploadBean")
      @Scope("request")
      public class FileUploadBean{
         
          private ArrayList<File> files = new ArrayList<File>();
          private int uploadsAvailable = 5;
          private boolean autoUpload = false;
          private boolean useFlash = true;
          private String userName;
          public int getSize() {
              if (getFiles().size()>0){
                  return getFiles().size();
              }else
              {
                  return 0;
              }
          }

       

          public FileUploadBean() {
          }

       

          public void paint(OutputStream stream, Object object) throws IOException {
              stream.write(getFiles().get((Integer)object).getData());
          }
          public void listener(UploadEvent event) throws Exception{
             UploadItem item = event.getUploadItem();
              File file = new File();
              file.setLength(item.getData().length);
              file.setName(item.getFileName());
              file.setData(item.getData());
              files.add(file);
              uploadsAvailable--;
          } 
           
          public String clearUploadData() {
              files.clear();
              setUploadsAvailable(5);
              return null;
          }
         
          public long getTimeStamp(){
              return System.currentTimeMillis();
          }
         
          public ArrayList<File> getFiles() {
              return files;
          }

       

          public void setFiles(ArrayList<File> files) {
              this.files = files;
          }

       

          public int getUploadsAvailable() {
              return uploadsAvailable;
          }

       

          public void setUploadsAvailable(int uploadsAvailable) {
              this.uploadsAvailable = uploadsAvailable;
          }

       

          public boolean isAutoUpload() {
              return autoUpload;
          }

       

          public void setAutoUpload(boolean autoUpload) {
              this.autoUpload = autoUpload;
          }

       

          public boolean isUseFlash() {
              return useFlash;
          }

       

          public void setUseFlash(boolean useFlash) {
              this.useFlash = useFlash;
          }

       

          public String getUserName() {
              return userName;
          }

       

          public void setUserName(String userName) {
              this.userName = userName;
          }

       

      }

       

       

       

      package backingBeans;

       

       

       

      public class File {

       

          private String Name;
          private String mime;
          private long length;
          private byte[] data;
          public byte[] getData() {
              return data;
          }
          public void setData(byte[] data) {
              this.data = data;
          }
          public String getName() {
              return Name;
          }
          public void setName(String name) {
              Name = name;
              int extDot = name.lastIndexOf('.');
              if(extDot > 0){
                  String extension = name.substring(extDot +1);
                  if("bmp".equals(extension)){
                      mime="image/bmp";
                  } else if("jpg".equals(extension)){
                      mime="image/jpeg";
                  } else if("gif".equals(extension)){
                      mime="image/gif";
                  } else if("png".equals(extension)){
                      mime="image/png";
                  } else if("image/jpeg".equals(extension)){
                      mime="image/jpeg";
                  } else {
                      mime = "image/unknown";
                  }
              }
          }
          public long getLength() {
              return length;
          }
          public void setLength(long length) {
              this.length = length;
          }
         
          public String getMime(){
              return mime;
          }
      }

        • 1. Re: rich:fileupload with request scope?
          Nick Belaevski Master

          Hi Mohtisham,

           

          a4j:mediaOutput downloads file contents in separate request(s), so you need to use scope with longer lifetime than request. You can try conversation scope existing in Seam.

          • 2. Re: rich:fileupload with request scope?
            Mohtisham Anwar Newbie

            Well, i have surely used that scope available in seam but as you can see i'm using spring so, how can i handle it?

            • 3. Re: rich:fileupload with request scope?
              Nick Belaevski Master

              Right - haven't noticed Spring annotations used in code. Conversation scope exists in WebFlow, so how about trying it?

              • 4. Re: rich:fileupload with request scope?
                Mohtisham Anwar Newbie

                Well, i have to do it with spring request scope all i can do is that i can chang my logic to display the picture either replace <a4j:mediaOutput with some other component or any change in my backend logic.

                • 5. Re: rich:fileupload with request scope?
                  Ilya Shaikovsky Master

                  just store your files not in this request scoped object but outject to some object with longer scope and use in 'paint' method.

                  • 6. Re: rich:fileupload with request scope?
                    Mohtisham Anwar Newbie

                    Well, i have tried through <a4j:keepAlive with so many ways like, i store the file on my computer and put the path of that file in keepalive bean. When i used the <h:outputText it showed me the path to that file. But when i used the <a4j:mediaOutput it again throw the null pointer exception i don't know what's wrong with the <a4j:mediaOutput. Everything works fine and the path is shown but there is something wrong with the <a4j:mediaOutput my code is as following:

                     

                     

                    package backingBeans;

                     

                    import java.io.File;
                    import java.io.FileInputStream;
                    import java.io.FileOutputStream;
                    import java.io.IOException;
                    import java.io.InputStream;
                    import java.io.OutputStream;
                    import java.io.Serializable;

                     

                    import org.richfaces.event.UploadEvent;
                    import org.richfaces.model.UploadItem;
                    import org.springframework.beans.factory.annotation.Autowired;
                    import org.springframework.context.annotation.Scope;
                    import org.springframework.stereotype.Component;

                     

                    @Component("fileUploadBean")
                    @Scope("request")
                    public class FileUploadBean implements Serializable{

                     

                        /**
                         *
                         */
                        private static final long serialVersionUID = 1L;
                        private int uploadsAvailable = 5;
                        private boolean autoUpload = false;
                        private boolean useFlash = false;
                        private PicturePath picturePath;
                        private String username;

                     

                        public String getUsername() {
                            return username;
                        }

                     

                        public void setUsername(String username) {
                            this.username = username;
                        }

                     

                        @Autowired
                        public FileUploadBean(PicturePath picturePath) {
                            this.picturePath = picturePath;
                        }

                     

                        public void paint(OutputStream stream, Object object) throws IOException {
                            stream.write(getBytesFromFile(new File(this.picturePath
                                    .getPicturePath())));
                        }

                     

                        public void listener(UploadEvent event) throws Exception {
                            UploadItem item = event.getUploadItem();
                            String dir = "C:";
                            File f = new File(dir);

                     

                            if (!f.exists()) {
                                f.mkdir();
                            }
                            f = new File(dir + "/" + item.getFileName());
                            this.picturePath.setPicturePath(f.getAbsolutePath());
                            FileOutputStream fos;
                            try {
                                fos = new FileOutputStream(f);
                                fos.write(item.getData());
                                fos.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            uploadsAvailable--;
                        }

                     

                        public long getTimeStamp() {
                            return System.currentTimeMillis();
                        }

                     

                        public int getUploadsAvailable() {
                            return uploadsAvailable;
                        }

                     

                        public void setUploadsAvailable(int uploadsAvailable) {
                            this.uploadsAvailable = uploadsAvailable;
                        }

                     

                        public boolean isAutoUpload() {
                            return autoUpload;
                        }

                     

                        public void setAutoUpload(boolean autoUpload) {
                            this.autoUpload = autoUpload;
                        }

                     

                        public boolean isUseFlash() {
                            return useFlash;
                        }

                     

                        public void setUseFlash(boolean useFlash) {
                            this.useFlash = useFlash;
                        }

                     

                        public PicturePath getPicturePath() {
                            return picturePath;
                        }

                     

                        public static byte[] getBytesFromFile(File file) throws IOException {

                     

                            InputStream is = new FileInputStream(file);
                            long length = file.length();
                            byte[] bytes = new byte[(int) length];

                     

                            int offset = 0;
                            int numRead = 0;
                            while (offset < bytes.length
                                    && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                                offset += numRead;
                            }

                     

                            if (offset < bytes.length) {
                                throw new IOException("Could not completely read file "
                                        + file.getName());
                            }

                     

                            is.close();
                            return bytes;
                        }

                     

                    }

                     

                     

                     

                    package backingBeans;

                     

                    import java.io.Serializable;

                     

                    import org.springframework.context.annotation.Scope;
                    import org.springframework.stereotype.Component;

                     

                    @Component("picturePath")
                    @Scope("request")
                    public class PicturePath implements Serializable{

                     

                       
                       
                        /**
                         *
                         */
                        private static final long serialVersionUID = 1L;
                        private String picturePath;

                     

                        public PicturePath() {

                     

                        }

                     

                        public String getPicturePath() {      
                            return picturePath;
                        }

                     

                        public void setPicturePath(String picturePath) {       
                            this.picturePath = picturePath;
                        }
                    }

                     

                    <?xml version='1.0' encoding='UTF-8' ?>
                    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                                          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                    <html xmlns="http://www.w3.org/1999/xhtml"
                        xmlns:ui="http://java.sun.com/jsf/facelets"
                        xmlns:f="http://java.sun.com/jsf/core"
                        xmlns:h="http://java.sun.com/jsf/html"
                        xmlns:a4j="http://richfaces.org/a4j"
                        xmlns:rich="http://richfaces.org/rich">

                     


                    <ui:composition template="layout.xhtml">
                        <ui:define name="title">Picture</ui:define>
                        <ui:define name="content">
                            <h:form>
                                <h:panelGrid columns="2" columnClasses="top,top">
                                    <rich:fileUpload fileUploadListener="#{fileUploadBean.listener}"
                                        maxFilesQuantity="#{fileUploadBean.uploadsAvailable}" id="upload"
                                        immediateUpload="#{fileUploadBean.autoUpload}"
                                        acceptedTypes="jpg, gif, png, bmp"
                                        allowFlash="#{fileUploadBean.useFlash}">
                                        <a4j:support event="onuploadcomplete" reRender="path,info" />
                                    </rich:fileUpload>
                                    <a4j:keepAlive beanName="picturePath" />
                                    <h:inputText value="#{fileUploadBean.username}" />
                                    <h:outputText value="#{picturePath.picturePath}"
                                                id="path" />               
                                                                 <a4j:mediaOutput element="img" mimeType="image/jpeg"
                                                        createContent="#{fileUploadBean.paint}"
                                                        style="width:100px; height:100px;" cacheable="false" id="info">
                                                        <f:param value="#{fileUploadBean.timeStamp}" name="time" />
                                                    </a4j:mediaOutput>
                                </h:panelGrid>
                            </h:form>
                        </ui:define>
                    </ui:composition>
                    </html>

                    • 7. Re: rich:fileupload with request scope?
                      Nick Belaevski Master

                      Everything works fine and the path is shown but there is something wrong with the <a4j:mediaOutput my code is as following:

                       

                      Hi Mohtisham,

                       

                      a4j:mediaOutput downloads file contents in separate request(s), so you need to use scope with longer lifetime than request. You can try conversation scope existing in Seam.

                      • 8. Re: rich:fileupload with request scope?
                        Mohtisham Anwar Newbie

                        Well, i have already clearly told you that, i don't want to use "seam" just becuase of this control why a new framework just for one control? According to you it is impossible to do it with request scope i got it; now let others to give answer.