Найти - Пользователи
Полная версия: Скачать фаил с сервера Django
Начало » Django » Скачать фаил с сервера Django
1
Malow
Доброго времени суток всем .у меня реализован на сайте не большой конвертер который берет ссылку с ютуба конвертирует ее в мр3 и отправляет на почту ссылку для скачивание конвертироного файла. фаил после конвертации попадает в папку media. и вот у меня вопрос как сделать чтоб после перехода по ссылке фаил скачивался пользывателю на комп?
фаил views.py

import youtube_dl
import os

from django.shortcuts import render, redirect
from django.contrib import messages
from converter.models import Converter
from converter.forms import ConvertForm
from django.core.mail import send_mail
from django.conf import settings
# from django.http import FileResponse

# Create your views here.


DOWNLOAD_OPTIONS_MP3 = {
'format': 'bestaudio/best',
'outtmpl': 'media/%(title)s.%(ext)s',
'nocheckcertificate': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}


def get_mp3(link, email, url):
with youtube_dl.YoutubeDL(DOWNLOAD_OPTIONS_MP3) as dl:
result = dl.extract_info(link)
filename = result['title']
download_link = 'http://' + url + '/media/' + filename.replace(' ', '_') + '.mp3'
send_mail('Ссылка на скачивание файла', download_link, settings.EMAIL_HOST_USER, [email], fail_silently=False, )



def get_link(request):
if request.method == 'POST':
form = ConvertForm(request.POST)
if form.is_valid():
link = form.cleaned_data.get('link')
email = form.cleaned_data.get('email')
query = Converter.objects.create(link=link, email=email)
url = request.get_host()
messages.success(request, 'Ссылка на скачивание отправлена на почту!')
get_mp3(link, email, url)
# return redirect('/')
else:
form = ConvertForm()

return render(request, 'index.html', locals())
kalkerre
У вас где развернуто приложение? Я бы рекомендовал для этих целей использовать не Djago, а прокси-сервер nginx, с mime-type octet-stream для файлов с определенным расширением (например mp3). Джанго генерирует ссылку - nginx ее сервит
romankrv
In order to create a download link, we need to create a Django view that would serve the files:

 # views.py
import mimetypes
def download_file(request):
    # fill these variables with real values
    fl_path = /file/path'
    filename = downloaded_file_name.extension
    fl = open(fl_path, 'r’)
    mime_type, _ = mimetypes.guess_type(fl_path)
    response = HttpResponse(fl, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % filename
        return response
#Once you've done this, add a line to urlpatterns in urls.py, which references the view.
# urls.py
path(<str:filepath>/, views.download_file)

How it works?
It works because we send the following HTTP header to a browser:

Content-Disposition: attachment; filename
It tells a browser to treat a response as a downloadable file. Have you noticed that we also include Content-Type header? This one tells what kind of file we are sending to the browser or in other words its mime type. If the header is not set Django will set it to text/html. mimetypes.guess_type is a handy function which tries to guess the mime type of the file, however if you know the mime type of your file(s) beforehand, it is better to set this manually.



Enjoy
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB