Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to download a filefield file in django view

I have filefield in my django model:

file=models.FileField(verbose_name=u'附件',upload_to='attachment/%Y/%m/%d',max_length=480)

This file will display in the web page with link "http://test.com.cn/home/projects/89/attachment/2012/02/24/sscsx.txt"

What I want to do is when user click the file link, it will download the file automatically; Can anyone tell me how to do this in the view?

Thanks in advance!

like image 457
Angelia Avatar asked Feb 27 '12 09:02

Angelia


People also ask

How to download a file in Django rest framework?

Now, open the urls.py file from the Django project and update the file with the following script. The text file will download if the path, 'download/' is used after the base URL. Open the browser and execute the following URL that will open the download dialog box for the user.

How to download in Django?

Django can be installed easily using pip . In the command prompt, execute the following command: pip install django . This will download and install Django. After the installation has completed, you can verify your Django installation by executing django-admin --version in the command prompt.


1 Answers

You can try the following code, assuming that object_name is an object of that model:

filename = object_name.file.name.split('/')[-1]
response = HttpResponse(object_name.file, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s' % filename

return response

See the following part of the Django documentation on sending files directly: https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment

like image 84
Victor Neo Avatar answered Sep 19 '22 18:09

Victor Neo