AnsweredAssumed Answered

Problem downloading file using Alfresco Webservice

Question asked by radheya on May 18, 2009
Latest reply on Dec 6, 2010 by mandavasateesh
Hi,
I'm developing a demo project on using Alfresco webservice to upload and download a file.
Now facing one peculiar problem while downloading. i.e. i can download a file which is uploaded into alfresco repository using Alfresco Web Client, but i'm unable to download when it is uploaded through my code(where i'm using Alfresco webservice).

I'd really appreciate a lot if anybody could look at this problem.

Following are the 2 servlets where i'm uploading and downloading a file respectively.


UploadFileAction.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  String msg="";
  try
  {
      String fileName="";
      String title=request.getParameter("title").trim();
      String description=request.getParameter("description").trim();
      String path = request.getParameter("file");
     
      path = path.replaceAll("\\\\", "/");
      fileName = path.substring(path.lastIndexOf('/')+1,path.length());
     
    String ext= fileName.substring(fileName.lastIndexOf('.')+1,fileName.length());
    String contType="";
   
    if(ext.equals("txt"))
      contType = "text/plain";
    else if (ext.equals("xls"))
      contType = "application/vnd.ms-excel";
    else if (ext.equals("doc"))
      contType = "application/msword";
    else if (ext.equals("html") || ext.equals("htm"))
      contType = "text/html";
    else if (ext.equals("jpg") || ext.equals("jpeg"))
      contType = "image/jpeg";
    else if (ext.equals("bmp"))
      contType = "image/bmp";
    else if (ext.equals("pdf"))
      contType = "application/pdf";
    else if (ext.equals("ppt"))
      contType = "application/vnd.ms-powerpoint";
    else if(ext.equals("xml"))
      contType = "text/xml";
    else if (ext.equals("zip"))
      contType = "application/vnd.ms-zip";
   
    if(contType.equals(""))
    {
      msg="Unknown file format. File not uploded.";
    }
    else
    {
        WebServiceFactory.setEndpointAddress("http://172.19.148.42:8080/alfresco/api");
        AuthenticationUtils.startSession("admin", "admin");
       
          // Create a reference to the parent where we want to create content
          Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
          ParentReference companyHomeParent = new ParentReference(storeRef, null, "/app:company_home/cm:bneps", Constants.ASSOC_CONTAINS, null);

          RepositoryServiceSoapBindingStub repositoryService =WebServiceFactory.getRepositoryService();
          ContentServiceSoapBindingStub contentService =WebServiceFactory.getContentService();
          NamedValue[] contentProps = new NamedValue[1];
          NamedValue[] titledProps = new NamedValue[2];

        // Assign name
          companyHomeParent.setChildName("cm:" + fileName);

          contentProps[0] = Utils.createNamedValue(Constants.PROP_NAME, fileName);
          //Construct CML statement to add titled aspect
          titledProps[0] = Utils.createNamedValue(Constants.PROP_TITLE, title);
          titledProps[1] = Utils.createNamedValue(Constants.PROP_DESCRIPTION, description);

          CMLAddAspect addAspect = new CMLAddAspect(Constants.ASPECT_TITLED, titledProps, null, "1");

          //create content
          // Construct CML statement to create content node
          // Note: Assign "1" as a local id, so we can refer to it in subsequent
          // CML statements within the same CML block
          CMLCreate create = new CMLCreate("1", companyHomeParent, companyHomeParent.getUuid(), Constants.ASSOC_CONTAINS, null, Constants.PROP_CONTENT, contentProps);
          // Construct CML Block
          CML cml = new CML();
          cml.setCreate(new CMLCreate[] {create});
          cml.setAddAspect(new CMLAddAspect[] {addAspect});
          // Issue CML statement via Repository Web Service and retrieve result
          // Note: Batching of multiple statements into a single web call
          UpdateResult[] result = repositoryService.update(cml);
          Reference content = result[0].getDestination();
          // Write some content
          FileInputStream is = new FileInputStream(path);
          byte[] bytes = ContentUtils.convertToByteArray(is);

          ContentFormat format = new ContentFormat(contType, "UTF-8");
          // Write the content
          contentService.write(content, Constants.PROP_CONTENT, bytes, format);
          msg="File Uploaded Successfully";
    }    
  }
  catch(Exception e)
  {
    msg="Error uploading file";
    System.out.println("Error uploading file : "+e);
    System.out.println(e.toString());
  }
  finally
  {
      // End the session
      AuthenticationUtils.endSession();
  }
  request.setAttribute("msg",msg);
  RequestDispatcher rd=request.getRequestDispatcher("StatusMessage.jsp");
  rd.forward(request,response);
}



DownloadFileAction.java

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
  String fileName=request.getParameter("fileName");

  WebServiceFactory.setEndpointAddress("http://172.19.148.42:8080/alfresco/api");
 
  /**Start the session*/
  AuthenticationUtils.startSession("admin", "admin");
 
  /** Make sure Service Folder has been created,or download files will be failure */
  boolean Success = true;
  Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
  String parentSpace = "/app:company_home/cm:bneps";
  Reference SAMPLE_FOLDER = new Reference(storeRef, null, parentSpace);
   
  try
  {
        WebServiceFactory.getRepositoryService().get(new Predicate(new Reference[]{SAMPLE_FOLDER}, storeRef, null));
  }
  catch (Exception exception)
  {
    System.out.println("Error while getting repository service");
    Success=false;
  }
 
  /**Download files,if exception then "Success = False" */
  try
  {
    if(Success)
    {
      ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
      Reference contentReference = new Reference(storeRef,null,parentSpace+"/cm:"+fileName);
      Content[] readResult = contentService.read(new Predicate(new Reference[]{contentReference}, storeRef, null), Constants.PROP_CONTENT);
      for(Content content: readResult)
      {
        String[] splitedUrl = content.getUrl().split("/");
        if(splitedUrl[splitedUrl.length-1].equals(fileName))
        {
         
            InputStream in=ContentUtils.getContentAsInputStream(content);
         
          response.reset();
          response.setHeader ("Content-Disposition", "attachment;filename=\""+fileName+"\"");
          ServletOutputStream sosStream = response.getOutputStream();

          int ibit = 256;
             while ((ibit) >= 0)
             {
                ibit = in.read();
                sosStream.write(ibit);
             }
            
             sosStream.flush();
             sosStream.close();
             in.close();
        }
      }
    }
  }
  catch(ClientAbortException e)
  {
    System.out.println("File download cancelled by the user");
  }
  catch(Exception e)
  {
    System.out.println("Error downloading file : "+e);
  }
  /** End the session*/
  AuthenticationUtils.endSession();
}


Thanks a lot
Radheya

Outcomes