环境
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