Django图片传输、视频传输和文件流式下载

注意:这是演示的代码,是把static的路径都加入到了settings.py文件中了

一、图片传输

# 图片传输
from django.http import FileResponse
def image(request):
    if request.method == 'GET':
        # 图片实际路径
        img_file = os.path.join(BASE_DIR, r'static\weichat\img\1.png')
        if not os.path.exists(img_file):
            return HttpResponse(content='文件不存在! ', status=200)
        else:
            data = open(img_file, 'rb')
            return FileResponse(data, content_type='image/png')
    pass

二、视频传输

# 视频传输
from django.http import FileResponse
def video(request):
    if request.method == 'GET':
        # 视频实际路径
        img_file = os.path.join(BASE_DIR, r'static\upfile\video\1.mp4')
        if not os.path.exists(img_file):
            return HttpResponse(content='文件不存在! ', status=200)
        else:
            data = open(img_file, 'rb')
            return FileResponse(data, content_type='video/mp4')
    pass

三、文件流式传输下载

from django.http import StreamingHttpResponse
def video(request):
    file_name = '1.mp4'
    response = StreamingHttpResponse(file_itrator())
    response['content_type'] = "application/octet-stream"
    response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name)
    return response

# 文件迭代
def file_itrator():
    file_path = os.path.join(BASE_DIR, r'static\upfile\video\1.mp4')
    chunk_size = 8192  # 每次读取的片大小
    with open(file_path, 'rb') as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break

 

你可能感兴趣的:(django学习)