django的预览文件接口及视频文件的分段读取数据

环境

ubuntu 20.04
python 3.6
django 2.2
最简单的是使用django的streamingHttpResponse库

from django.http import StreamingHttpResponse
try:
    # 这里创建返回
    response = StreamingHttpResponse(open(path, 'rb'))
    # 注意格式
    response['Content-Type'] = 'image/png'
    response['Content-Disposition'] = 'inline;filename=%s' % 'test.png'
    # # 文件长度
    response['content-length'] = '12342341'
    return response
except:
    print('预览失败')

如果文件太大的话就不适合使用streamingHttpResponse这个类,可以使用FileResponse,这个是streamingHttpResponse类的子类,使用迭代器的方式把文件分成很多小份依次返回

from django.http import FileResponse
try:
    # 这里创建返回  其中data为文件二进制字节流bytes类型的
    response = FileResponse(open(path, 'rb'))
    # 注意格式
    response['Content-Type'] = 'image/png'
    response['Content-Disposition'] = 'inline;filename=%s' % 'test.png'
    # # 文件长度
    response['content-length'] = '12342341'
    return response
except:
    print('预览失败')

在使用uwgis+django时会报io.UnsupportedOperation: fileno,问题原因uwsgi不支持这种方式的处理需要进行二次处理,解决办法

from wsgiref.util import FileWrapper
response = FileResponse(FileWrapper(open(path, 'rb')))

播放视频时如果需要拖动进度条,则使用下面方法,代码来源

import re
import os
from wsgiref.util import FileWrapper
from django.http import StreamingHttpResponse
 
def file_iterator(file_name, chunk_size=8192, offset=0, length=None):
    with open(file_name, "rb") as f:
        f.seek(offset, os.SEEK_SET)
        remaining = length
        while True:
            bytes_length = chunk_size if remaining is None else min(remaining, chunk_size)
            data = f.read(bytes_length)
            if not data:
                break
            if remaining:
                remaining -= len(data)
            yield data
 
def stream_video(request, path):
    """将视频文件以流媒体的方式响应"""
    range_header = request.META.get('HTTP_RANGE', '').strip()
    range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I)
    range_match = range_re.match(range_header)
    size = os.path.getsize(path)
    content_type, encoding = mimetypes.guess_type(path)
    content_type = content_type or 'application/octet-stream'
    if range_match:
        first_byte, last_byte = range_match.groups()
        first_byte = int(first_byte) if first_byte else 0
        last_byte = first_byte + 1024 * 1024 * 8       # 8M 每片,响应体最大体积
        if last_byte >= size:
            last_byte = size - 1
        length = last_byte - first_byte + 1
        resp = StreamingHttpResponse(file_iterator(path, offset=first_byte, length=length), status=206, content_type=content_type)
        resp['Content-Length'] = str(length)
        resp['Content-Range'] = 'bytes %s-%s/%s' % (first_byte, last_byte, size)
    else:
        # 不是以视频流方式的获取时,以生成器方式返回整个文件,节省内存
        resp = StreamingHttpResponse(FileWrapper(open(path, 'rb')), content_type=content_type)
        resp['Content-Length'] = str(size)
    resp['Accept-Ranges'] = 'bytes'
    return resp
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值