Django 文件上传和下载功能

文件下载功能

相应内容除了返回网页的信息外,还可以实现文件的下载功能,Django提供三种下载文件的功能,分别是:HttpResponse,StreamingHttpResponse,FileResponse.

  • HttpResponse:是所有响应过程的核心类,它的底层功能类是HttpResponseBase
  • StreamingHttpResponse:是在HttpResponseBase的基础上进行继承和重写的,它实现流式响应输出(是使用python的迭代器将数据进行分段处理并输出)。适用于大型规模数据响应和文件传输响应
  • FileResponse:是在StreamingHttpResponse的基础上继承重写的,它实现文件的流式响应输出,只适合用于文件传输和响应
class StreamingHttpResponse(HttpResponseBase):
    
    streaming = True

    def __init__(self, streaming_content=(), *args, **kwargs):
        super().__init__(*args, **kwargs)
        # `streaming_content` should be an iterable of bytestrings.
        # See the `streaming_content` property methods.
        self.streaming_content = streaming_content
  • streaming_content:的数据格式可设为迭代器对象或字节流,代表数据或文件内容
  • *args, **kwargs:设置HttpResponseBase的参数,即响应内容的数据格式,content_type和响应状态码status等参数。

若使用StreamingHttpResponswene实现文件下载,则文件以字节的方式读取,在StreamingHttpResponse实列化时传入文件的字节流,由于该类支持数据或文件内容的响应方式输出,因此还需设置响应内容的数据格式和文件下载格式

class FileResponse(StreamingHttpResponse):
    """
    A streaming HTTP response class optimized for files.
    """
    block_size = 4096

    def __init__(self, *args, as_attachment=False, filename='', **kwargs):
        self.as_attachment = as_attachment
        self.filename = filename
       
  • 6
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值