Sending video as response in django

2019-05-06 17:05发布

问题:

How to send a video mp4 file as a response in django? I don't want to embed in a video or object tags of html, but want to send the mp4 itself. Can anyone please help with this issue?

回答1:

Generally you don't want to do this; it's better to redirect to a non-Django server to serve static files, with e.g. django.shortcuts.redirect -- it'll be faster, more memory-efficient, and probably more secure. But of course sometimes that's not convenient. This should work:

from wsgiref.util import FileWrapper

file = FileWrapper(open('path/to/video.mp4', 'rb'))
response = HttpResponse(file, content_type='video/mp4')
response['Content-Disposition'] = 'attachment; filename=my_video.mp4'
return response

The FileWrapper (docs) is used so that too much data isn't sent at once, since Python file objects iterate a line at a time, and \n characters presumably aren't especially common in mp4s. (Sending too much means that the webserver can't send the file as it's read off the hard drive but instead has to wait for long awkwardly-spaced increments.)

Note that although I don't see this noted in the documentation anywhere, the file does get closed when it's done with.