how to download a filefield file in django view

强颜欢笑 提交于 2019-11-26 21:37:57

问题


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!


回答1:


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




回答2:


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 }}.



来源:https://stackoverflow.com/questions/9462999/how-to-download-a-filefield-file-in-django-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!