how to download a filefield file in django view
Asked Answered
C

3

20

I have filefield in my django model:

class MyModel(Model):
    file = models.FileField(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!

Curvature answered 27/2, 2012 at 9:52 Comment(0)
U
33

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

Unloose answered 27/2, 2012 at 11:9 Comment(4)
how did you get object_name to that view? what URL params did you use?Yaker
The object_name doesn't matter as it simply represents a Django Model object. You can retrieve the object any way you like.Unloose
You could also use os.path.basename to filter filename instead of using .split('/'). eg. filename = os.path.basename(object_name.file.name). This will work regardless of OS.Dyarchy
what if the filename is UTF-8 string?Chronogram
L
6

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.storage

All that will be stored in your database is a path to the file (relative to MEDIA_ROOT). You'll most likely want to use the convenience url function provided by Django. For example, if your ImageField is called mug_shot, you can get the absolute path to your image in a template with {{ object.mug_shot.url }}.

Laryngoscope answered 27/2, 2012 at 10:40 Comment(0)
C
0

You can do this with a FileResponse like so:

def download_file_view(request, id):
    object = get_object_or_404(MyModel, id)

    # Create FileResponse
    return FileResponse(
        object.file.open(),
        as_attachment=True,
        filename=object.file.name
    )
Chongchoo answered 30/5 at 21:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.