How to send video(mp4) as a response

I need to know how i can send a video file as a response in django.

React+Django

this is my djanog code which is handling the request.

u/csrf_exempt
def get_video(request):
    view_logger.info("Fetching video")
    try:
        if not LOGS_FOLDER_PATH:
            view_logger.warning("LOGS FOLDER PATH not present")
            return HttpResponseNotFound("Logs folder path not set.")

        videos_path = os.path.join(LOGS_FOLDER_PATH, "videos")
        if not os.path.exists(videos_path):
            return HttpResponseNotFound("Videos folder does not exist.")

        videos_list = os.listdir(videos_path)
        if not videos_list:
            return HttpResponseNotFound("No videos found.")

        video_path = os.path.join(videos_path, videos_list[0])
        view_logger.info(f"Video path:- {video_path}")
        video_response = FileResponse(
            open(video_path, 'rb'),
        )
        view_logger.info(f"\n\n\n{video_response}")
        return video_response

    except Exception as error:
        view_logger.error(f"Error fetching terminal video. Error: {error}")
        return JsonResponse({'error': 'Internal server error'}, status=500)

LOGS_FOLDER_PATH - I can't add this as static cuz I receive this during runtime.

React Code:-

import React from "react";
import "./CSS/VideoDisplay.css";

const VideoDisplay = ({ api_url_name }) => {
  return (
    <div className="video-display-div">
      <video width="100%" controls aria-label="video">
        <source src={`${api_url_name}/api/dashboard/get-video/`} type="video/mp4" />
        Your browser does not support the video tag.
      </video>
    </div>
  );
};

export default VideoDisplay;

I tried returning the video as response using FileResponse but the video is not displaying the Frontend.

You’re very close — the backend is correctly returning the file using FileResponse, but to make a video stream playable in a browser (especially through the tag), a few key things must be ensured:

Set the Correct Content-Type

Ensure that the FileResponse is set with the right MIME type for the video. For .mp4, this should be:

from django.http import FileResponse, HttpResponseNotFound, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import os

@csrf_exempt
def get_video(request):
    view_logger.info("Fetching video")
    try:
        if not LOGS_FOLDER_PATH:
            view_logger.warning("LOGS FOLDER PATH not present")
            return HttpResponseNotFound("Logs folder path not set.")

        videos_path = os.path.join(LOGS_FOLDER_PATH, "videos")
        if not os.path.exists(videos_path):
            return HttpResponseNotFound("Videos folder does not exist.")

        videos_list = os.listdir(videos_path)
        if not videos_list:
            return HttpResponseNotFound("No videos found.")

        video_path = os.path.join(videos_path, videos_list[0])
        view_logger.info(f"Video path:- {video_path}")

        # Ensure the correct content type
        return FileResponse(open(video_path, 'rb'), content_type='video/mp4')

    except Exception as error:
        view_logger.error(f"Error fetching terminal video. Error: {error}")
        return JsonResponse({'error': 'Internal server error'}, status=500)

Found what the issue was, the size of video file was small for it to be played it video player. Checked with bigger video file size, it worked.

You better provide MIME type by requesting the video type from the API response header instead of hardcoding it to video/mp4 since there are ogg, mpeg, quicktime, etc videos.

You can use mimetypes module to obtain it like:

import mimetypes

video_path = "path/to/video"
content_type = mimetypes.guess_type(video_path)[0]

return FileResponse(open(video_path, 'rb'), content_type=content_type)
Back to Top