def toFieldValue(self, value):

        if value is None or value == '':
            return self.field.missing_value

        if INamed.providedBy(value):
            return value

        elif utils.is_file_upload(value):

            filename = safe_basename(value.filename)

            if filename is not None and isinstance(filename, six.binary_type):
                # Work-around for
                # https://bugs.launchpad.net/zope2/+bug/499696
                filename = filename.decode('utf-8')

            value.seek(0)
            data = value.read()
            if data or filename:
                return self.field._type(data=data, filename=filename)
            else:
                return self.field.missing_value

        else:
            if isinstance(value, six.text_type):
                value = value.encode('utf-8')
            return self.field._type(data=value)
示例#2
0
    def toFieldValue(self, value):

        if value is None or value == '':
            return self.field.missing_value

        if INamed.providedBy(value):
            return value
        elif isinstance(value, FileUpload):

            filename = safe_basename(value.filename)

            if filename is not None and not isinstance(filename, unicode):
                # Work-around for
                # https://bugs.launchpad.net/zope2/+bug/499696
                filename = filename.decode('utf-8')

            value.seek(0)
            data = value.read()
            if data or filename:
                return self.field._type(data=data, filename=filename)
            else:
                return self.field.missing_value

        else:
            return self.field._type(data=str(value))
示例#3
0
    def toFieldValue(self, value):

        if value is None or value == '':
            return self.field.missing_value

        if INamed.providedBy(value):
            return value
        elif isinstance(value, FileUpload):

            filename = safe_basename(value.filename)

            if filename is not None and not isinstance(filename, unicode):
                # Work-around for
                # https://bugs.launchpad.net/zope2/+bug/499696
                filename = filename.decode('utf-8')

            value.seek(0)
            data = value.read()
            if data or filename:
                return self.field._type(data=data, filename=filename)
            else:
                return self.field.missing_value

        else:
            return self.field._type(data=str(value))
 def filename(self):
     if INamed.providedBy(self.value):
         return self.value.filename
     elif utils.is_file_upload(self.value):
         return safe_basename(self.value.filename)
     else:
         return None
示例#5
0
    def toFieldValue(self, value):
        
        if value is None or value == '':
            return self.field.missing_value

        if INamed.providedBy(value):
            return value
        elif isinstance(value, FileUpload):
            
            headers = value.headers
            filename = safe_basename(value.filename)
            
            if filename is not None and not isinstance(filename, unicode):
                # Work-around for
                # https://bugs.launchpad.net/zope2/+bug/499696
                filename = filename.decode('utf-8')
            
            contentType = 'application/octet-stream'
            if headers:
                contentType = headers.get('Content-Type', contentType)
            
            value.seek(0)
            data = value.read()
            if data or filename:
                return self.field._type(data=data, contentType=contentType, filename=filename)
            else:
                return self.field.missing_value
        
        else:
            return self.field._type(data=str(value))
 def filename(self):
     if self.field is not None and self.value == self.field.missing_value:
         return None
     elif INamed.providedBy(self.value):
         return self.value.filename
     elif isinstance(self.value, FileUpload):
         return safe_basename(self.value.filename)
     else:
         return None
示例#7
0
 def filename(self):
     if self.field is not None and self.value == self.field.missing_value:
         return None
     elif INamed.providedBy(self.value):
         return self.value.filename
     elif isinstance(self.value, FileUpload):
         return safe_basename(self.value.filename)
     else:
         return None
示例#8
0
    def getImage(self, value):
        widget = self.widget
        req = widget.request

        if isinstance(value, FileUpload):

            filename = safe_basename(value.filename)

            if filename is not None and not isinstance(filename, unicode):
                # Work-around for
                # https://bugs.launchpad.net/zope2/+bug/499696
                filename = filename.decode('utf-8')

            value.seek(0)
            data = value.read()
            if data or filename:
                value = self.field._type(data=data, filename=filename)
            else:
                return self.get_missing_image()

        else:
            args = {}
            if req.get(widget.name + '.filename'):
                filename = req.get(widget.name + '.filename')
                if type(filename) in (list, set, tuple) and filename:
                    filename = filename[0]
                if not isinstance(filename, unicode):
                    filename = filename.decode('utf8')
                args['filename'] = filename
            if isinstance(value, basestring):
                if value.startswith('reference:'):
                    reference = value.replace('reference:', '')
                    obj = uuidToObject(reference)
                    if obj:
                        try:
                            try:
                                ct = obj.image.contentType
                            except AttributeError:
                                ct = None
                            value = NamedBlobImage(contentType=ct)
                            alsoProvides(value, IReferenceNamedImage)
                            value.reference = reference
                        except AttributeError:
                            pass
                elif value.startswith('data:'):
                    value = b64decode(value.split(',')[-1])
                    value = self.field._type(data=value, **args)
            else:
                try:
                    value = self.field._type(data=str(value), **args)
                except UnicodeEncodeError:
                    value = self.field._type(data=value.encode('utf8'), **args)

        return value
    def _toFieldSubValue(self, value, current_field_value):
        """
        Converts a subvalue to an `INamedFile`.

        Parameters:
        value -- The value extracted from the request by the widget.
        current_field_value -- The current value of the field on the context.

        Return:
        a value of the fields value_type or it's `missing_value` if the value cannot be converted.

        See plone.formwidget.namedfile.converter.NamedDataConverter
        """

        value_type = self.field.value_type._type
        missing_value = self.field.value_type.missing_value

        if value is None or value == '':
            return missing_value
        elif INamed.providedBy(value):
            return value
        elif isinstance(value, basestring) and value.startswith('index:'):
            # we already have the file
            index = int(value.split(':')[1])
            try:
                return current_field_value[index]
            except IndexError:
                return missing_value
        elif isinstance(value, FileUpload):
            # create a new file

            headers = value.headers
            filename = safe_basename(value.filename)
            if filename is not None and not isinstance(filename, unicode):
                # Work-around for
                # https://bugs.launchpad.net/zope2/+bug/499696
                filename = filename.decode('utf-8')

            contentType = 'application/octet-stream'
            if headers:
                contentType = headers.get('Content-Type', contentType)

            value.seek(0)
            data = value.read()
            if data or filename:
                return value_type(data=data, contentType=contentType, filename=filename)
            else:
                return missing_value

        else:
            return value_type(data=str(value))
示例#10
0
    def toFieldValue(self, value):

        filename = None
        data = None

        if INamed.providedBy(value):
            filename = value.filename
            data = value.data

        elif isinstance(value, FileUpload):
            filename = safe_basename(value.filename)
            value.seek(0)
            data = value.read()

        if not data:
            return self.field.missing_value

        return b64encode_file(filename, data)
示例#11
0
    def toFieldValue(self, value):

        filename = None
        data = None

        if INamed.providedBy(value):
            filename = value.filename
            data = value.data

        elif isinstance(value, FileUpload):
            filename = safe_basename(value.filename)
            value.seek(0)
            data = value.read()

        if not data:
            return self.field.missing_value

        return b64encode_file(filename, data)
        def replace_link(link):
            if not match(link):
                return link

            try:
                f = self.url_opener.open(link)
            except urllib2.HTTPError:
                return link
            except urllib2.URLError as error:
                logger.warning('Could not replace link %s in %s: %s' % (
                    link, '/'.join(self.context.getPhysicalPath()), error
                ))
                return link

            path = urlparse.urlparse(link).path
            filename = unicode(urllib.quote(safe_basename(path)))

            key = cache_keys.getKey(link)
            value = self.image_blob_factory(f.read(), filename=filename)

            cache_manager.add(key, self.context, value)
            return prefix + urllib.quote(key, safe='')
示例#13
0
        def replace_link(link):
            if not match(link):
                return link

            try:
                f = self.url_opener.open(link)
            except urllib2.HTTPError:
                return link
            except urllib2.URLError as error:
                logger.warning(
                    'Could not replace link %s in %s: %s' %
                    (link, '/'.join(self.context.getPhysicalPath()), error))
                return link

            path = urlparse.urlparse(link).path
            filename = unicode(urllib.quote(safe_basename(path)))

            key = cache_keys.getKey(link)
            value = self.image_blob_factory(f.read(), filename=filename)

            cache_manager.add(key, self.context, value)
            return prefix + urllib.quote(key, safe='')
示例#14
0
    def extract(self, default=NOVALUE):
        url = self.request.getURL()
        action = self.request.get("%s.action" % self.name, None)
        if url.endswith('kss_z3cform_inline_validation')\
                or url.endswith('z3cform_validate_field'):
            # Ignore validation requests.
            action = 'nochange'

        if action == 'remove':
            return None
        elif action == 'nochange':
            if self.value is not None:
                return self.value

            if url.endswith('z3cform_validate_field'):
                # Ignore validation requests.
                return None

            # Handle already uploaded files in case of previous form errors
            file_upload_id = self.request.get(
                "%s.file_upload_id" % self.name
            ) or 0
            if file_upload_id:
                upload_map = IFileUploadTemporaryStorage(getSite()).upload_map
                fileinfo = upload_map.get(file_upload_id, {})
                filename = fileinfo.get('filename')
                data = fileinfo.get('data')

                if filename or data:
                    if filename:
                        filename = safe_basename(filename)
                    if (
                            filename is not None
                            and not isinstance(filename, six.text_type)
                    ):
                        # work-around for
                        # https://bugs.launchpad.net/zope2/+bug/499696
                        filename = filename.decode('utf-8')
                    del upload_map[file_upload_id]
                    value = {
                        'data': data,
                        'filename': filename,
                    }
                    ret = _make_namedfile(value, self.field, self)
                    return ret

            if self.ignoreContext:
                return default
            dm = getMultiAdapter((self.context, self.field,), IDataManager)
            # For sub-widgets to function use a query() not get()
            data = dm.query(default)
            data = _make_namedfile(data, self.field, self.context)
            return data

        # empty unnamed FileUploads should not count as a value
        value = super(NamedFileWidget, self).extract(default)
        if utils.is_file_upload(value):
            value.seek(0, SEEK_END)
            empty = value.tell() == 0
            value.seek(0)
            if empty and not value.filename:
                return default
            value.seek(0)
        return value