---
title: "django返回一个文件"
author: "listen-raining"
date: "2016-05-24T16:03:32Z"
tags: []
categories: ["Web前端"]
slug: "django"
draft: false
lastmod: "2016-05-24T16:03:32Z"
id: 2300604
url: "https://listen-raining.iteye.com/blog/2300604"
---

版本：django1.9.5


def downloadFile2(req):
    log.info('下载文件..............')
    downpath = None
    if req.POST:
        downpath=req.POST.get('downpath',None)
    else:
        downpath=req.GET.get('downpath',None)

    log.info('当前的下载路径是........')
    log.info(downpath)
    if downpath is not None:
        def file_iterator(downpath,chunk_size=512):
            with open(downpath) as f:
                while True:
                    c = f.read(chunk_size)
                    if c:
                        yield c
                    else:
                        break
        file_name = downpath.split("/")
        response = StreamingHttpResponse(file_iterator(downpath))
        response = 'application/octet-stream'
        response = 'attachment;filename="{0}"'.format(file_name)
        return response
    else:
        print '路径不正确'