美文网首页
Django 实现文件下载

Django 实现文件下载

作者: Leebor | 来源:发表于2017-12-21 17:03 被阅读0次
    上篇有【文件上传】,算是完成了一个比较完整的项目。
    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>
    

    相关文章

      网友评论

          本文标题:Django 实现文件下载

          本文链接:https://www.haomeiwen.com/subject/auyawxtx.html