将视频从服务器下载到用户机器作为django中的响应



我用django和youtubedl编写了一个小型的any视频下载程序。每当用户试图下载视频时,它都会在服务器内的文件夹/home/SERVER_USER_NAME/Downloads中下载。现在我如何告诉浏览器将该视频下载到用户的本地机器上?我已经编写了一个方法serve_file(),但它不起作用。

#!/usr/bin/env python3
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from .forms import AnyVideoDownloadForm
import youtube_dl
import os
from django.contrib import messages
from mimetypes import MimeTypes
from urllib.request import pathname2url
from django.http import HttpResponse
URL_LIST = ''
# Create your views here.
def home(request):
global URL_LIST
if request.method == 'POST':
form = AnyVideoDownloadForm(request.POST)
if form.is_valid():
URL_LIST = form.cleaned_data['url']
return redirect('anydownload')
else:
form = AnyVideoDownloadForm()
return render(request, 'anyvideo/home.html', {'form': form})

def serve_file(): 
file_path = '/home/SERVER_USER_NAME/Downloads/video.mp4'
filename = os.path.basename(file_path)
mime = MimeTypes()
url = pathname2url(file_path)
mimetype, encoding = mime.guess_type(url)
f = open(file_path, 'rb')
response = HttpResponse(f.read(), content_type=mimetype)
response['Content-Length'] = os.path.getsize(file_path)
response['Content-Disposition'] = 
"attachment; filename="%s"; filename*=utf-8''%s" % 
(filename, filename)
f.close()
return response
def anydownload(request):
if request.method == 'GET':
ydl_opts = {
# 'logger': MyLogger(),
'quiet': True,
'skip_download': True,
'match_filter': youtube_dl.utils.match_filter_func("!is_live"),
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
meta = ydl.extract_info(URL_LIST, download=False)
context = {
'title': (f"{meta['title']}"),
'uploader': (f"{meta['uploader']}"),
}
return render(request, 'anyvideo/anydownload.html', context)
if request.method == 'POST':
ydl_opts = {
'format': 'best',
'outtmpl': '~/Downloads/video.mp4',
'noplaylist': True,
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([URL_LIST])
serve_file() #<-------called above method here
messages.success(request, 'Video has been successfully downloaded !')
return redirect('anyhome')
return render(request, "anyvideo/anydownload.html")

您的代码几乎是正确的,但您只需要更改一件事。请把完整的源代码发给我。试试这个代码:

#!/usr/bin/env python3
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from .forms import AnyVideoDownloadForm
import youtube_dl
import os
from django.contrib import messages
from mimetypes import MimeTypes
from urllib.request import pathname2url
from django.http import HttpResponse
URL_LIST = ''
# Create your views here.
def home(request):
global URL_LIST
if request.method == 'POST':
form = AnyVideoDownloadForm(request.POST)
if form.is_valid():
URL_LIST = form.cleaned_data['url']
return redirect('anydownload')
else:
form = AnyVideoDownloadForm()
return render(request, 'anyvideo/home.html', {'form': form})

def serve_file(): 
file_path = '/home/SERVER_USER_NAME/Downloads/video.mp4'
filename = os.path.basename(file_path)
mime = MimeTypes()
url = pathname2url(file_path)
mimetype, encoding = mime.guess_type(url)
f = open(file_path, 'rb')
response = HttpResponse(f.read(), content_type=mimetype)
response['Content-Length'] = os.path.getsize(file_path)
response['Content-Disposition'] = 
"attachment; filename="%s"; filename*=utf-8''%s" % 
(filename, filename)
f.close()
return response
def anydownload(request):
if request.method == 'GET':
ydl_opts = {
# 'logger': MyLogger(),
'quiet': True,
'skip_download': True,
'match_filter': youtube_dl.utils.match_filter_func("!is_live"),
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
meta = ydl.extract_info(URL_LIST, download=False)
context = {
'title': (f"{meta['title']}"),
'uploader': (f"{meta['uploader']}"),
}
return render(request, 'anyvideo/anydownload.html', context)
if request.method == 'POST':
ydl_opts = {
'format': 'best',
'outtmpl': '~/Downloads/video.mp4',
'noplaylist': True,
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([URL_LIST])
serve_file() #<-------called above method here
messages.success(request, 'Video has been successfully downloaded !')
return serve_file()
return render(request, "anyvideo/anydownload.html")

请将完整的源代码发给我

最新更新