如何重命名Python金字塔响应对象中的文件? [英] How can I rename a file in a Python Pyramid Response object?

查看:21
本文介绍了如何重命名Python金字塔响应对象中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
How to set file name in response

我在MongoDB中存储文件。为了提供来自金字塔的文件,我这样做:

# view file
def file(request):
    id = ObjectId(request.matchdict['_id'])
    collection = request.matchdict['collection']
    fs = GridFS(db, collection)
    f = fs.get(id)
    filename, ext = os.path.splitext(f.name)
    ext = ext.strip('.')
    if ext in ['pdf','jpg']:
        response = Response(content_type='application/%s' % ext)
    else:
        response = Response(content_type='application/file')
    response.app_iter = FileIter(f)
    return response

使用此方法,文件名默认为文件的ObjectId字符串,该字符串不美观,并且缺少正确的文件扩展名。我在文档中查看了如何/在哪里重命名Response对象中的文件,但我看不到它。任何帮助都是极好的。

推荐答案

没有100%万无一失的方法来设置文件名。文件名由浏览器决定。

也就是说,您可以使用Content-Disposition头指定希望浏览器下载文件而不是显示该文件,您还可以建议该文件使用的文件名。如下所示:

Content-Disposition: attachment; filename="fname.ext"

但是,没有可靠的跨浏览器方法来指定包含非ASCII字符的文件名。有关详细信息,请参阅this stackoverflow question。您还必须小心对文件名使用quoted-string编码;构建一个文件名时,应删除所有非ASCII字符,并使用"加引号。

现在是金字塔特有的东西。只需在您的响应中添加一个Content-Disposition头。(请注意,application/filenot a valid mime type。使用application/octet-stream作为"通用"字节袋类型。)

# "application/file" is not a valid mime type!
content_subtype = ext if ext in ['jpg','pdf'] else 'octet-stream'

# This replaces non-ascii characters with '?'
# (This assumes f.name is a unicode string)
content_disposition_filename = f.name.encode('ascii', 'replace')

response = Response(content_type="application/%s" % content_subtype,
                    content_disposition='attachment; filename="%s"' 
                      % content_disposition_filename.replace('"','\"')
           )

这篇关于如何重命名Python金字塔响应对象中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆