使用django的框架,发现用chrome浏览器时,video的进度无法拖动
总结网上的方法,发现使用StreamingHttpResponse可以解决此问题
StreamingHttpResponse是将文件内容进行流式传输。它将数据持续的传输,实现续点传输,还降低了内存的消耗。
修改了大神的代码,如下
解决方法:
HTML 部分:
<video id="example" class="vjs-default-skin vjs-big-play-centered" poster="{% static '/imgs/v1.jpg'%}" controls preload="auto" >
<source style=" background:#000;" src="/video/stream_video" type="video/mp4">
<p class="vjs-no-js"> To view this video please enable JavaScript, and consider upgrading to a web browser</p>
</video>
url.py 部分:
path('stream_video', stream_video, name='stream_video'),
app.py 部分:
from wsgiref.util import FileWrapper
from django.http import StreamingHttpResponse
import mimetypes
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):
""" responds to the video file as """
path='static/media/show.mp4' #此为我的视频路径
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()
if first_byte:
first_byte = int(first_byte)
else:
first_byte = 0
last_byte = first_byte + 1024 * 1024 * 8 # 8M per piece, the maximum volume of the response body
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:
# When the video stream is not obtained, the entire file is returned in the generator mode to save memory.
resp = StreamingHttpResponse(FileWrapper(open(path, 'rb')), content_type=content_type)
resp['Content-Length'] = str(size)
resp['Accept-Ranges'] = 'bytes'
return resp
当然也可以写成def stream_video(request,path):再引入path
用以上方法即可解决进度条无法拖动的问题