Django FileResponse下载文件

django FileResponse下载文件

代码如下:

from django.http import FileResponse

  def get(self, request, *args, **kwargs):
        file_path = /Users/zonghan/Desktop/1.txt
        return FileResponse(
            open(file_path, "rb"),  # 被下载文件的路径
            filename=os.path.basename(file_path),  # 文件名称
            as_attachment=True
        )

该文件会自动关闭,所以不要用上下文管理器打开它。

如果 as_attachment=TrueContent-Disposition 头被设置为 attachment,要求浏览器将文件作为下载文件提供给用户。否则,只有在有文件名的情况下,才会设置值为 inlineContent-Disposition 头(浏览器默认)。

如果 open_file 没有名字,或者 open_file 的名字不合适,可以使用 filename 参数提供一个自定义的文件名。请注意,如果你传递了一个类似文件的对象,比如 io.BytesIO,你的任务是在把它传递给 FileResponse 之前 seek(0)

to_zip.seek(0)  # to_zip为BytesIO对象
return FileResponse(
    to_zip, filename="yyy.zip", as_attachment=True
)

如果用postman测试的话,点击如下按钮

image

如果上面代码有问题可以使用下面的例子
image

posted @ 2022-11-01 16:56  zong涵  阅读(548)  评论(0编辑  收藏  举报