django返回一个文件

版本: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("/")[-1]
        response = StreamingHttpResponse(file_iterator(downpath))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(file_name)
        return response
    else:
        print '路径不正确'

猜你喜欢

转载自listen-raining.iteye.com/blog/2300604