Django 实现文件下载

2017-12-21  本文已影响0人  Leebor
上篇有【文件上传】,算是完成了一个比较完整的项目。
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>
上一篇下一篇

猜你喜欢

热点阅读