好,上传了文件,咱们接下来就来下载吧(。。。这么无聊?)
路由配置
比起上传,下载要简单点,首先做一下下载的连接,修改 index.html 文件,将待完善的连接写上:
1
| <li><a href="{% url 'blog.views.download' f=file.file.url %}">{{ file.name }}</a></li>
|
配置 URL ,添加如下一行:
1
| url(r'^download/(?P<f>.*)$', download, name = "download"),
|
后台逻辑
去写 views 方法,views.py 中添加:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| def download(request, f): t = f.split("/") file_name = t[-1] t.remove(t[-1]) t.remove(t[0]) file_path = "/".join(t) def file_iterator(file_name, file_path, chunk_size=512): path = file_path +"/" + file_name with open(path) as f: while True: c = f.read(chunk_size) if c: yield c else: break try: response = StreamingHttpResponse(file_iterator(file_name, file_path)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(file_name) except: return HttpResponse("Sorry but Not Found the File") return response
|
其中涉及到下载文件的分块,因为大文件如果一次性的读入会太占内存。
好了,不出意外的话,上传、下载应该都好了。
最后,还有一个坏消息,如果你的项目和我一样是部署在 SAE 上的,那么,想实现文件上传、下载,这么做还不够,因为需要按照 SAE 的规则来,可以参考 SAE 的官方文档:link.