0

I want to download a file from a URL. Actually, I want to get the file from a URL and return it when the user requests to get that file for download. I am using this codes:

def download(request):
    file = 'example.com/video.mp4''
    name = 'file name'
    response = HttpResponse(file)
    response['Content-Disposition'] = f'attachment; filename={name}'
    return response

but it cant return file for download. These codes return a file, but the file is not in the URL. how can I fix it?

1 Answers1

0

Try this code,

import requests
from django.http import HttpResponse

def download_file(request):
    # URL of the file you want to download
    file_url = 'https://example.com/path/to/your/file.txt'

    # Fetch the file from the URL
    response = requests.get(file_url)

    if response.status_code == 200:
        # Set the file name for the downloaded file
        filename = 'downloaded_file.txt'

        # Create an HttpResponse with the file content and appropriate headers
        response = HttpResponse(
            response.content,
            content_type='application/octet-stream'
        )
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        return response
    else:
        return HttpResponse("Failed to download the file.")
  • These codes download the file first and then give it to the user. And it is not used for large files. In fact, it makes the user wait for a long time to download – user17657114 Aug 23 '23 at 17:30