May 3, 2021, 10:23 a.m.

" How to download a file in django | Making a large file downloadable from a url in django | How to serve Large files in django | Downloading a file from Django project directory "

Sometimes we have to serve a file which may be a large file from our project directory. Suppose you want to transfer a file from your project directory to your friend or to some other person/server/platform. The one way is to download the file and then upload it to another platform or give it to the person manually, which is not a good approach.

This is a simple thing in Django. You can serve any file from any directory (i.e inside project directory) using a URL in Django. Just follow the steps shown below and you will find that some line of code will help you to do that.

If file is binary: Add the following url in urlpatterns.
#In urls.py
path('download/',views.download,name="download"),

Now set the function in views.py i.e. download() as mapped in urls.py
#In views.py
from django.http import FileResponse
import os

def download(request):
  file_path = os.path.join(BASE_DIR, 'myfile.zip')
  response = FileResponse(open(file_path, 'rb'))
  return response

So now if someone visits "www.example.com/download" the downloading of file i.e "myfile.zip" will starts.
Note that if the file is not binary then you have to use 'r' instead of 'rb' in your code.

If file is a text/utf-8 file: If you only want to show the text content of the file then you can use the following code:
#In views.py
from django.http import FileResponse
import os

def download(request):
  file_path = os.path.join(BASE_DIR, 'requirement.txt')
  f = open(file_path, 'r')
  file_content = f.read()
  f.close()
  return HttpResponse(file_content, content_type="text/javascript")

In this case the text content of the file will be server in the browser or client device.

Now, if the file is strored in database models/fields then you can do something like this:
#In views.py
from django.http import FileResponse
import os

def download(request):
  obj=mymodel.objects.get(id=someid)
  response = FileResponse(open(obj.fileField.path, 'rb'))
  return response






Some recent posts



Complete process of changing database from SQLite to MySQL - How to migrat...

" How to download a file in django | Making a large file downloadable from ...

How to use proxy in python requests | http & https proxies - Scraping...

Top Django Querysets, How to filter records | Fetching data from database e...

How to change base url or domain in sitemap - Django ...

How to Make a Website - Everything you should know about web development...

What is Javascript - Features and usages ...

Top 5 Interview Questions : Tips for HR round ...

How to get job in IT : Perfect resume guide for IT job ...

Programming vs coding | difference between programming and coding ...



View all...

Image NOt Found Purna poddar -
- May 7, 2021, 2:11 p.m.