Subida y descarga de un fichero

cancel
Showing results for 
Search instead for 
Did you mean: 
scm
Member II

Subida y descarga de un fichero

Hola buenas,

Estoy realizando un programa que me permita subir y descargar un fichero con web services. El caso es que me lo sube correctamente, pero no me deja descargarlo. En cambio, si en vez de subirlo a través de mi aplicación, lo hago desde el propio Alfresco, sí puedo descargarlo a través de mi aplicación.
Por ello supongo que el problema está en la subida, que me faltará algo que sea necesario detectar en la descarga.

Adjunto el código de la subida:
public class UploadAction extends Action {
      
   String loginName = StandardSQLUserProfileDAO.loginName;
   
   public ActionForward execute(ActionMapping mapping, ActionForm form,
         HttpServletRequest request, HttpServletResponse response)
         throws Exception {

      if (!(form instanceof UploadForm)) {
         return mapping.findForward(mapping.getInput());
      }

      System.out.println("Executing AddContentAction…");
      
      // Recogemos los parametros del fichero
      UploadForm theForm = (UploadForm) form;
      FormFile theFile = theForm.getTheFile();
      String contentType = theFile.getContentType();
      String fileName = theFile.getFileName();
      int fileSize = theFile.getFileSize();
      byte[] fileData = theFile.getFileData();
      String description = theForm.getDescription();
      String id = UploadContentAction.id;
      String destinatario = UploadContentAction.destinatario;
   
      System.out.println(" > Nombre: " + fileName);
      System.out.println(" >   Tipo: " + contentType);
      System.out.println(" > Tamaño: " + fileSize);
      System.out.println(" > Descripcion: " + description);
      System.out.println(" > Id procedimiento: " + id);
      System.out.println(" > Destinatario: " + destinatario);

      try
           {
              AuthenticationUtils.startSession("admin", "admin");
              
              Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
              Reference reference = new Reference(storeRef, null, "/app:company_home/*[@cm:name=\"" + "User Homes" + "\"]/*[@cm:name=\"" + destinatario + "\"]");

              ParentReference parentRef = new ParentReference();
              parentRef.setStore(storeRef);
              parentRef.setUuid(reference.getUuid());
              parentRef.setPath(reference.getPath());
              parentRef.setAssociationType(Constants.ASSOC_CONTAINS);
              parentRef.setChildName(Constants.ASSOC_CONTAINS);
             
              // Comienza la construcción de nodo
             
              NamedValue[] contentProps = new NamedValue[5];
              contentProps[0] = Utils.createNamedValue(Constants.PROP_NAME, fileName);
              contentProps[1] = Utils.createNamedValue(Constants.PROP_TITLE, "1");
              contentProps[2] = Utils.createNamedValue("{http://www.alfresco.org/model/content/1.0}email-id", id);
              contentProps[3] = Utils.createNamedValue(Constants.PROP_DESCRIPTION, description);
              contentProps[4] = Utils.createNamedValue("{http://www.alfresco.org/model/content/1.0}author", loginName);
             
              CMLCreate create = new CMLCreate();
              create.setParent(parentRef);
              create.setProperty(contentProps);
              create.setType(Constants.TYPE_CONTENT);
             
              CML cml = new CML();
              cml.setCreate(new CMLCreate[] {create});
                        
              UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml);
              Reference content = result[0].getDestination();
             
              ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
              ContentFormat contentFormat = new ContentFormat(contentType, "UTF-8");
              contentService.write(content, Constants.PROP_CONTENT, bytes, contentFormat);
          }
         
           catch (Exception e) {
               throw new InternalErrorException(e);
           }
         
          finally
          {
              AuthenticationUtils.endSession();
          }
   
      return mapping.findForward("HomePage");
   }
}

Y el código de descarga:
public class DescargarAction extends DefaultAction {
   
    public ActionForward doExecute(ActionMapping mapping,
        ActionForm form, HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException, InternalErrorException {
       
       String loginName = StandardSQLUserProfileDAO.loginName;
       String fileName = request.getParameter("name");

      /**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:name=\"" + "User Homes" + "\"]/*[@cm:name=\"" + loginName + "\"]";
      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);
            Predicate pred = new Predicate(new Reference[]{contentReference}, storeRef, null);
            Content[] readResult = contentService.read(pred, 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.getMessage());
      }
   
      AuthenticationUtils.endSession();
      return mapping.findForward(mapping.getInput());
    }
}

Si alguien me pudiera ayudar lo agradecería.
Muchas gracias.
2 Replies
sergiocm
Member II

Re: Subida y descarga de un fichero

¿Nadie sabe el problema?
lupiska
Member II

Re: Subida y descarga de un fichero

Hola, pudiste resolverlo?? me interesa el tema que estas tratando porque tambien estoy realizando algo parecido…