cancel
Showing results for 
Search instead for 
Did you mean: 

unzip a file after upload

roeland19
Champ in-the-making
Champ in-the-making
Is there a way i can directly unzip a zipped file after i upload it ? I have
searched for some examples but i couldn't find any.
18 REPLIES 18

janvg
Champ in-the-making
Champ in-the-making
What I was thinking is that if I export a space I get a ACP file. This means Alfresco uses some protocol to create ACP files.

Is there a tool to create an ACP file from a folder on my c drive as if I was using some kind of ZIP program ? Would it be possible to import this ACP file using the Alfresco Import function ?

gavinc
Champ in-the-making
Champ in-the-making
Hi,

An ACP file is just a ZIP file in structure (a bit like a JAR and WAR file is just a zip file). It just has a certain structure and contents.

So, yes, in theory it is possible to create an ACP file from folders on your disk and then import them into Alfresco, but no such tool exists!

Have a look at an existing ACP file and read the wiki page on import export to get an idea of the contents and structure you need.

davidetaibi
Champ in-the-making
Champ in-the-making
I write the following code to unzip files in an alfresco space after upload.

package org.alfresco.repo.action.executer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipException;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.action.ParameterDefinitionImpl;
import org.alfresco.repo.action.executer.ActionExecuterAbstractBase;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.dictionary.InvalidAspectException;
import org.alfresco.service.cmr.dictionary.InvalidTypeException;
import org.alfresco.service.cmr.model.FileExistsException;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.ContentIOException;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.InvalidNodeRefException;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.InvalidQNameException;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.TempFileProvider;
import org.alfresco.web.bean.repository.Repository;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

/**
* Zip action executor
*
* @author Davide Taibi
*/
public class ZipActionExecuter extends ActionExecuterAbstractBase
{
   public static final String NAME = "importzip";
   public static final String PARAM_ENCODING = "encoding";
   public static final String PARAM_DESTINATION_FOLDER = "destination";

   private static final String TEMP_FILE_PREFIX = "alf";
   private static final String TEMP_FILE_SUFFIX = ".zip";

   /**
    * The node service
    */
   private NodeService nodeService;

   /**
    * The content service
    */
   private ContentService contentService;

   private MimetypeService mimetypeService;
   private FileFolderService fileFolderService;

   /**
    * Sets the NodeService to use
    *
    * @param nodeService The NodeService
    */
   public void setNodeService(NodeService nodeService)
   {
      this.nodeService = nodeService;
   }

   /**
    * Sets the ContentService to use
    *
    * @param contentService The ContentService
    */
   public void setContentService(ContentService contentService)
   {
      this.contentService = contentService;
   }

   public void setFileFolderService(FileFolderService fileFolderService) {
      this.fileFolderService = fileFolderService;
   }

   public void setMimetypeService(MimetypeService mimetypeService) {
      this.mimetypeService = mimetypeService;
   }

   private void extractFile(ZipFile archive,String mExtractToDir){
      String fileName;
      String destFileName;
      byte[] buffer = new byte[16384];
      mExtractToDir=mExtractToDir+File.separator;
      try {
         for ( Enumeration e = archive.getEntries(); e.hasMoreElements(); )
         {
            ZipEntry entry = (ZipEntry)e.nextElement();
            if ( ! entry.isDirectory() )
            {
               fileName = entry.getName();
               fileName = fileName.replace('/', File.separatorChar);
               destFileName = mExtractToDir + fileName;
               File destFile = new File(destFileName);
               String parent = destFile.getParent();
               if ( parent != null )
               {
                  File parentFile = new File(parent);
                  if ( ! parentFile.exists() )
                     parentFile.mkdirs();
               }
               InputStream in = archive.getInputStream(entry);
               OutputStream out = new FileOutputStream(destFileName);
               int count;
               while ( (count = in.read(buffer)) != -1 )
                  out.write(buffer, 0, count );
               in.close();
               out.close();
            }else{
               File newdir = new File( mExtractToDir + entry.getName() );
               newdir.mkdir();
            }
         }
      } catch (ZipException e) {
         e.printStackTrace();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }   

   private void deleteDir(File dir){
         File elenco=new File(dir.getPath());
         for (File file:elenco.listFiles()){
            if (file.isFile())
               file.delete();
            else
               deleteDir(file);
         }
         dir.delete();
   }
   
   public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {
      String spaceType;
      NodeRef parentNodeRef;
      FileInfo fileInfo;
      NodeRef nodeRef;

      if (this.nodeService.exists(actionedUponNodeRef) == true) {
         ContentReader reader = this.contentService.getReader(
               actionedUponNodeRef, ContentModel.PROP_CONTENT);
         if (reader != null) {
            if (MimetypeMap.MIMETYPE_ZIP.equals(reader.getMimetype())) {
               File zFile = null;
               ZipFile zipFile = null;
               try {
                  spaceType = ContentModel.TYPE_FOLDER.toString();
                  String dirName = ""+this.nodeService.getProperty(actionedUponNodeRef, ContentModel.PROP_NAME);
                  dirName=dirName.substring(0,dirName.indexOf(".zip"));
                  parentNodeRef = (NodeRef)ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER);// this.nodeService.getRootNode(Repository.getStoreRef());
                  fileInfo = fileFolderService.create(
                        parentNodeRef,
                        dirName,
                        Repository.resolveToQName(spaceType));
                  nodeRef = fileInfo.getNodeRef();

                  zFile = TempFileProvider.createTempFile(
                        TEMP_FILE_PREFIX, TEMP_FILE_SUFFIX);
                  reader.getContent(zFile);
                  zipFile = new ZipFile(zFile, "Cp437");
                  File tempDir=new File(TempFileProvider.getTempDir().getPath()+File.separator+dirName);
                  if (tempDir.exists()) deleteDir(tempDir);
                  extractFile(zipFile,tempDir.getPath());
                  importFile(tempDir.getPath(),nodeRef);
                  deleteDir(tempDir);
               } catch (ContentIOException e) {
                  e.printStackTrace();
               } catch (InvalidNodeRefException e) {
                  e.printStackTrace();
               } catch (FileExistsException e) {
                  e.printStackTrace();
               } catch (IOException e) {
                  e.printStackTrace();
               }
            }
         }
      }
   }

   private void importFile(String dir,NodeRef root){
      File elenco=new File(dir);
      for (File file:elenco.listFiles()){
         try {
            if (file.isFile()){
               InputStream contentStream = new FileInputStream(file);
               // assign name
               String fileName=file.getName();
               Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
               contentProps.put(ContentModel.PROP_NAME, fileName);
               // create content node
               ChildAssociationRef association = nodeService
               .createNode(
                     root,
                     ContentModel.ASSOC_CONTAINS,
                     QName.createQName(
                           NamespaceService.CONTENT_MODEL_PREFIX,
                           fileName),
                           ContentModel.TYPE_CONTENT,
                           contentProps);
               NodeRef content = association.getChildRef();
               // add titled aspect (for Web Client display)
               Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>();
               titledProps.put(ContentModel.PROP_TITLE, fileName);
               titledProps.put(ContentModel.PROP_DESCRIPTION,fileName);
               nodeService.addAspect(content,
                     ContentModel.ASPECT_TITLED,
                     titledProps);
               ContentWriter writer = contentService.getWriter(content,
                     ContentModel.PROP_CONTENT, true);
               writer.setMimetype(mimetypeService.guessMimetype(file.getAbsolutePath()));
               writer.setEncoding("Cp437");
               writer.putContent(contentStream);          
            }else{
               String spaceType = ContentModel.TYPE_FOLDER.toString();
               FileInfo fileInfo = fileFolderService.create(
                     root,
                     file.getName(),
                     Repository.resolveToQName(spaceType));

               importFile(file.getPath(),fileInfo.getNodeRef());
            }
         } catch (InvalidTypeException e) {
            e.printStackTrace();
         } catch (InvalidAspectException e) {
            e.printStackTrace();
         } catch (InvalidQNameException e) {
            e.printStackTrace();
         } catch (ContentIOException e) {
            e.printStackTrace();
         } catch (FileNotFoundException e) {
            e.printStackTrace();
         } catch (InvalidNodeRefException e) {
            e.printStackTrace();
         } catch (FileExistsException e) {
            e.printStackTrace();
         }
      }
   }

   protected void addParameterDefinitions(List<ParameterDefinition> paramList)
   {
      paramList.add(new ParameterDefinitionImpl(PARAM_DESTINATION_FOLDER, DataTypeDefinition.NODE_REF,
            true, getParamDisplayLabel(PARAM_DESTINATION_FOLDER)));
      paramList.add(new ParameterDefinitionImpl(PARAM_ENCODING, DataTypeDefinition.TEXT,
            true, getParamDisplayLabel(PARAM_ENCODING)));
   }
}


Moreover I write the file importzip-action-messages.properties :

importzip.title=Import Zip File
importzip.description=This Action import zip file into alfresco
importzip.aspect-name.display-label=The name of the aspect to apply to the node.

and add the following line to my …-context.xml, (you can use action-services-context.xml)

   <bean id="importzip" class="org.alfresco.repo.action.executer.ZipActionExecuter" parent="action-executer">
        <property name="nodeService">
            <ref bean="NodeService"></ref>
        </property>
        <property name="contentService">
            <ref bean="ContentService" />
        </property>
        <property name="mimetypeService">
            <ref bean="MimetypeService"></ref>
        </property>
                <property name="fileFolderService">
            <ref bean="FileFolderService"></ref>
        </property>
  </bean>
   <bean id="importzip-messages" class="org.alfresco.i18n.ResourceBundleBootstrapComponent">
       <property name="resourceBundles">
          <list>
             <value>org.alfresco.repo.action.importzip-action-messages</value>
          </list>
       </property>
      </bean>

and finally I add this line to my web-client-config-custom.xml

<config evaluator="string-compare" condition="Action Wizards">
      <action-handlers>
         <handler name="importzip" class="org.alfresco.web.bean.actions.handlers.ImportHandler" />
      </action-handlers>        
</config>

I hope this can help.

gavinc
Champ in-the-making
Champ in-the-making
This is great and something that would be very useful in the core product.

Would you consider officially contributing this? Have a look over the following wiki pages, especially the latter one:

http://wiki.alfresco.com/wiki/Contribution_Area
http://wiki.alfresco.com/wiki/Source_Code

davidetaibi
Champ in-the-making
Champ in-the-making
I uploaded the patch in a new jira ticket of type Contribution in the Alfresco Repository project. AR-862

gavinc
Champ in-the-making
Champ in-the-making
Thanks very much.

azade
Champ in-the-making
Champ in-the-making
hi
i want to do same work when upload zip file
please say me
where these codes must  add in alfresco??
please help me

jeyaa
Champ in-the-making
Champ in-the-making
Hi,

I tried the above code for Importing files from a zip. But when I execute action I am getting the following error.

Failed to run Actions due to error: 11070005 Found 1 integrity violations: The association source type is incorrect: Source Node: workspace://SpacesStore/cccf520c-8c16-43ef-a50e-0f90f252a686 Association: Association[ class=ClassDef[name={http://www.alfresco.org/model/content/1.0}folder], name={http://www.alfresco.org/model/content/1.0}contains, target class={http://www.alfresco.org/model/system/1.0}base, source role=null, target role=null] Required Source Type: {http://www.alfresco.org/model/content/1.0}folder Actual Source Type: {http://www.alfresco.org/model/system/1.0}store_root


Regards
Jai

mrogers
Star Contributor
Star Contributor
You need to extract the contents into a folder.   You are trying to extract to a "store root".
Getting started

Tags


Find what you came for

We want to make your experience in Hyland Connect as valuable as possible, so we put together some helpful links.