赶快记录一下写的一个django下载文件的例子,以便以后复习:
在views.py中设置
- from django.core.servers.basehttp import FileWrapper
- import mimetypes
- import settings
- import os
- def file_download(request, filename):
- filepath = os.path.join(settings.MEDIA_ROOT, filename)
- print (filepath)
- wrapper = FileWrapper(open(filepath, 'rb'))
- content_type = mimetypes.guess_type(filepath)[0]
- response = HttpResponse(wrapper, mimetype='content_type')
- response['Content-Disposition'] = "attachment; filename=%s" % filename
- return response
在settings.py中设置:
- import os
- STATIC_URL = '/static/'
- HERE = os.path.dirname(__file__)
- MEDIA_ROOT = HERE+STATIC_URL
最后在settings.py同一目录下设置一个文件夹static。 在文件价中添加文件1.ipg
在url.py中设置:
- url('^fileDownload/filename=(?P<filename>.{1,500})/$', 'DjangoDemo2.views.file_download'),#download
在浏览器中输入:
url :http://localhost:8000/fileDownload/filename=1.jpg/即可下载。