2

So I'm building a RESTful API for a "Development Platform" project using Django and want to setup a upload/download feature where the users of the platform can upload various files (Excel files, css files, pdf files, C# scripts, unity packages, blender files etc) and other users can then download these files through an endpoint. I have the upload file endpoint configured and properly working.

At the download file endpoint, I want to receive the filename that the user wants to download and also verify the user's credentials and permissions for downloading that file and do some other model queries and checks too and finally find that file in my /media/ folder and serve it to the user's browser for auto downloading or a download pop-up on the browser. (This download file endpoint would get hit when user presses "Download File" button on the frontend).

How can I achieve this in django? Could someone provide a sample piece of code to "send" that file, once fetched from the media folder, as a response to the user's browser for downloading?

1 Answers1

0

You can write a function for download like as below.

def download(request,file_name):
  file_path = settings.MEDIA_ROOT +'/'+ file_name
  file_wrapper = FileWrapper(file(file_path,'rb'))
  file_mimetype = mimetypes.guess_type(file_path)
  response = HttpResponse(file_wrapper, content_type=file_mimetype )
  response['X-Sendfile'] = file_path
  response['Content-Length'] = os.stat(file_path).st_size
  response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) 

  return response

Basically in reposne you have to set X-Sendfile, Content-Disposition, Content-Length which are important. And in front end you can something like: <a href="{file_path}" download></a>

You can also check below links which may help you to get your answer.

Django download a file

Downloading the files(which are uploaded) from media folder in django 1.4.3

https://ednsquare.com/question/how-to-serve-downloadable-files-using-django------9lAMsr

Dcoder14
  • 1,831
  • 3
  • 12
  • 22
  • Thanks for answering! I did all this and am getting a 200 on the endpoint which shows its working fine. I checked the response headers also, its showing the file name and the content length fine. But the download isn't starting on the browser. Nor am I getting a pop-up for download. Could you help with that? Is there something more I have to do on the frontend? PS. I am testing on my local machine and not on a server. – Divyansh Agarwal Apr 22 '20 at 09:34
  • yes,in front end you have to do like to make it work – Dcoder14 Apr 22 '20 at 13:05
  • Do i have to return an HttpResponse with all these headers and along with this on the frontend I have to create a download link? Assuming that in the frontend I already have the full path to the file? – Divyansh Agarwal Apr 24 '20 at 06:49