方式一:读入内存后输出下载

此方式会耗费较大的内存,要服务器崩溃很容易。

def file_download(request):
    downfilename = "filename.txt"

    with open('filename.txt') as f:
        c = f.read()

    response = HttpResponse(c)
    response['Content-Type'] = "application/octet-stream"
    response['Content-Disposition'] = 'attachment;filename="%s.xlsx"' % (quote(downfilename))
    return response

方式二:使用迭代器

block_size = 4096

downfilename = request.GET.get("filename", u"比赛排名").encode("utf-8")
filelike = file(file_full_path, "rb")

response = StreamingHttpResponse()
response.streaming_content = iter(lambda: filelike.read(block_size), '')
response['Content-Type'] = "application/octet-stream"
response['Content-Disposition'] = 'attachment;filename="%s.xlsx"' % (quote(downfilename))

方式三:yield,并使用with处理异常

downfilename = request.GET.get("filename", u"比赛排名").encode("utf-8")

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

response = StreamingHttpResponse()
response.streaming_content = file_iterator(file_full_path)
response['Content-Type'] = "application/octet-stream"
response['Content-Disposition'] = 'attachment;filename="%s.xlsx"' % (quote(downfilename))
return response

注意使用rb方式打开,否则你的Excel将打不开。

[ 编辑 | 历史 ]
最近由“jilili”在“2017-05-30 13:45:41”修改