【问题标题】:How can I rename a file in a Python Pyramid Response object? [duplicate]如何重命名 Python Pyramid 响应对象中的文件? [复制]
【发布时间】:2012-10-16 04:25:30
【问题描述】:

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

我将文件存储在 MongoDB 中。为了从 Pyramid 提供文件,我这样做:

# 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 对象内的文件,但我看不到它。任何帮助都会很棒。

【问题讨论】:

    标签: python response pyramid


    【解决方案1】:

    看来您必须设置 Content-Disposition 标头:

    response.content_disposition = 'attachment; filename=%s' % filename
    

    【讨论】:

    • 给你的虚拟六包,我的朋友。
    【解决方案2】:

    没有 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('"','\\"')
               )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-13
      • 2019-10-15
      • 2021-11-02
      • 1970-01-01
      • 2021-12-04
      • 2016-06-13
      • 2011-12-18
      • 1970-01-01
      相关资源
      最近更新 更多