Upload files as custom content type [SOLVED]

I made a dexterity content type ('TaggedText') which has a field 'qrktext' (and some other fields, also a rich text field)

Is it possible to 'batch upload' files (of type/filename something.xtg) to make (TaggedText) content, where the qrktext field gets 'the content of the (text) file' ?

The content is 'just text, utf-8', and the title of the content can be the filename…

What?

Look into transmogrify suite of libraries.

@espenmn the content_type_registry (http://demo.plone.de/content_type_registry/manage_predicates) is used to control which type will be created when uploading files. Simply change the type for the extensions you want to use.

If you need even more control you can override CustomFileFactory in a overrides.zcml:

<configure xmlns="http://namespaces.zope.org/zope">
  <adapter factory=".factories.CustomFileFactory" />
</configure>

Then write your own magic

# -*- coding: utf-8 -*-
from plone.app.dexterity.interfaces import IDXFileFactory
from plone.app.dexterity.factories import DXFileFactory
from Products.CMFCore.interfaces._content import IFolderish
from zope.component import adapter
from zope.interface import implementer


@adapter(IFolderish)
@implementer(IDXFileFactory)
class CustomFileFactory(DXFileFactory):

    def __call__(self, name, content_type, data):
        custom_obj = self.create_custom_stuff(name, content_type, data)
        if custom_obj:
            return custom_obj

        return super(CustomFileFactory, self).__call__(name, content_type, data)

    def create_custom_stuff(self, name, content_type, data):
        if name == 'superfile':
            # do you own stuff here like wrap each file in a folder
            return 'foo'
        return

Look at the original DXFileFactory for inspiration.

2 Likes

Thanks a lot.

For later reference:
The DXFilefactory approach did not work for the custom field, since it was a behaviour. If I added the field directly to the content type, it worked.

plone.api does not seem to have 'the same problem', so I used that:

obj = api.content.create(
         self.context,
         type_,
         qrktext=data.read(),
         title = name,
        )

obj.reindexObject()
return obj

For reference (and since I struggled to find it):

To get the encoding of the uploaded text, I used this:

    def create_custom_stuff(self, name, content_type, data):
        if name.endswith("xtg"):
            type_ = 'quarktags'
            name = name.decode('utf8')
            qrktext = data.read()
            the_encoding = chardet.detect(qrktext)['encoding']
            qrktext = qrktext.decode(the_encoding).encode("utf-8")
            
            obj = api.content.create(
                self.context,
                type_,
                qrktext=qrktext,
                title = name,
            )
            obj.reindexObject()
            return obj

        return False