## Script (Python) "download"
##title=Download a file keeping the original uploaded filename
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath

NotFound = "NotFound"
request = context.REQUEST
response = request.RESPONSE

if len(traverse_subpath) != 1:
    raise NotFound, "Unknown page."

name = traverse_subpath[0]
field = context.getField(name)

if not field:
    raise NotFound, "Unknown page."

accessor = field.getAccessor(context)

if accessor is None:
    raise NotFound, "Unknown page."

obj = accessor()

if hasattr(obj.aq_explicit, 'download'):
    return obj.download(request)
else:
    data = ''
    filename = ''
    content_type = 'application/octet-stream'
    size = 0
    
    if hasattr(obj.aq_explicit, 'data'):
        # handle OFS.Image.File and OFS.Image.Image
        data = str(obj.data)
        filename = obj.title
        content_type = obj.getContentType()
        size = obj.get_size()
    else:
        data = str(obj)
        size = len(data)
        
    response.setHeader('Content-Disposition',
                       'attachment; filename="%s"' % filename)
    response.setHeader('Content-Type', content_type)
    response.setHeader('Content-Length', size)
    response.write(data)
