Django 实现文件下载

上篇有【文件上传】,算是完成了一个比较完整的项目。
1.下载页面
image.png
2.下载页面代码

def file_iterator(file_name, chunk_size=1024):
    with open(file_name) as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break

def FileDownload(request):
    if request.method == 'GET':
        FilePath = request.GET['filepath']
        FileName = str(FileInfo.objects.get(FileField=FilePath).FileName)
        response = StreamingHttpResponse(file_iterator(FilePath))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename=%s' % FileName
        return response
        # print FilePath
    else:
        return HttpResponse('method must be get')
4.URL配置
    url(r'^download/', views.FileDownload),

3.下载页面前端代码
<div class="panel-body">
                <table class="table File-List-index-Table">
            <tr>
                <th>Id</th>
                <th>项目</th>
                <th>名称</th>
                <th>备注</th>
                <th>上传时间</th>
                <th>下载</th>
            </tr>
            {% if list == '' %}
                <span></span>
            {% else %}
                {% for m in list %}
                    <tr>
                        <td>{{ m.id }}</td>
                        <td>{{ m.ProName }}</td>
                        <td>{{ m.Filename }}</td>
                        <td>{{ m.Content }}</td>
                        <td>
                            <script>
                                document.write((new Date({{ m.UpdateTime }} * 1000).toLocaleString()))
                            </script>
                        </td>
                        <td><a href="/download/?filepath={{ m.FileField }}">下载</a></td>
                    </tr>
                {% endfor %}
            {% endif %}
        </table>
            </div>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,090评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,323评论 19 139
  • 我也会想到死亡<刘晨.著> 我四十岁了,有时会想到死亡, 甚至想到墓碑。 有时候会有疼痛来拉扯我一下。 我知道那是...
    明初的日记本阅读 4,093评论 0 0
  • 今天 我需要一个猫一样的情人 用带倒刺的温柔的舌头 舐遍我的心 所有的情绪都消散在喵喵声里 我重新变得柔软
    有北阅读 1,365评论 0 0
  • 在当今这个“没事看运势,有事转锦鲤”的社会,星座在各种社交场合的交谈中正扮演着重要的角色,今天小草莓化身“同道大婶...
    刘口水并不是流口水阅读 4,032评论 0 0