Getting default image when streaming a video onto the webpage through django
My moto:-* create a webpage which accepts a video file and once submitted through submit button, the video(in form of frames) will display within samepage in another div section. reason for displaying as frames is i need to process each frame. (Rendering frames onto webpage).*
My django code:def gen(request): if request.method == 'POST': try: video_file = request.FILES["video"] if video_file: video_filename = "temp_video.mp4" video_filepath = os.path.join(settings.STATIC_ROOT, video_filename) with open(video_filepath, 'wb') as destination: for chunk in video_file.chunks(): destination.write(chunk) video_cap = cv2.VideoCapture(video_filepath) if not video_cap.isOpened(): print("Error: Could not open video file") return "Error in processing video." while True: ret, frame = video_cap.read() if not ret: break else: #cv2.imshow("output",frame) tried this too but not working. frame_bytes = frame.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n\r\n') else: print("no video file") except Exception as e: print("An error occurred:", e) return "An error occurred while processing the video." def process_video(request): return StreamingHttpResponse(gen(request),content_type='multipart/x-mixed-replace; boundary=frame')
My javascript(in html file):-<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script> document.getElementById('uploadForm').addEventListener('submit', function (event) { event.preventDefault(); // Prevent default form submission behavior const formData = new FormData(this); fetch(this.action, { method: this.method, body: formData}) .then(response => { // Handle response // Define a function to handle each frame received function handleFrame(frameUrl) { // Create a new image element var img = $('<img>') .attr('src', frameUrl) .attr('height', '100px') .attr('width', '100px'); $('#video-display').empty().append(img);} // Create a function to process the streaming response function processResponse(response) { var contentType = response.headers.get('content-type'); if (contentType && contentType.indexOf('multipart/x-mixed-replace') !== -1) {const reader = response.body.getReader(); async function read() { while (true) { // Read the next chunk const { done, value } = await reader.read(); // If the chunk is done, break the loop if (done) { break;} // Convert the chunk to a blob and create a URL for it const blob = new Blob([value], { type: 'image/jpeg' }); const imageUrl = URL.createObjectURL(blob); // Handle the frame handleFrame(imageUrl);}} // Start reading chunks read();}} // Process the streaming response processResponse(response);}) .catch(error => { console.error('Error:', error);});}); </script>
My html:-
{% load static %}
<!DOCTYPE html>
<form class="home-form" id="uploadForm" action="{% url 'process_video' %}" method="post"
enctype="multipart/form-data">
{% csrf_token %}
<input type="file" accept="video" id="video-file" name="video"
placeholder="Enter your video here" class="home-input input" />
<div class="home-container08">
<button type="reset" class="home-button button">
<span>
<span>Reset</span>
<br />
</span>
</button>
<button type="submit" class="home-button1 button">Submit</button>
</div>
</form> <div id="video-display" class="home-container16">
</div>
My terminal:-
February 19, 2024 - 16:04:33
Django version 5.0.2, using settings 'final.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[19/Feb/2024 16:04:50] "GET / HTTP/1.1" 200 9358
[19/Feb/2024 16:05:07] "POST /process-video/ HTTP/1.1" 200 846041346
urls.py in my app:-
from django.urls import path
from . import views
urlpatterns= [
path("",views.home,name="home"),
path('process-video/', views.process_video, name='process_video'),]
urls.py in django project:-
from django.contrib import admin
from django.urls import path,include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("myapp.urls"))
]
# Add staticfiles_urlpatterns to urlpatterns
urlpatterns += staticfiles_urlpatterns()
The output was like this enter image description here This is my file structure enter image description here
The icon image was updating too but the images are not being displayed, the video is being stored in static files as expected too.
please help me out. thanks in advance.
This didn't work for me. so, Instead of the StreamingResponse i used the socket programming. It worked well than just yielding the frames on to the webpage. use relavent libraries to access the socket programming and return frames through emit function.