天天看點

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