django +StreamingHttpResponse文件下载

一、StreamingHttpResponse

可以实现文件按流下载,在下载大文件时,StreamingHttpResponse下载是一个比较高效,迭代下载的过程,这减轻了内存的压力。

二、代码实现

import os
from django.http import StreamingHttpResponse
from django.shortcuts import render, get_object_or_404

# Create your views here.
from django.utils.encoding import escape_uri_path

from serviceApp.models import Doc


def read_file(file_name, size):
    """分批读取文件"""
    with open(file_name, mode='rb') as fp:
        while True:
            c = fp.read(size)
            if c:
                # 生成器,相当于一个特殊的迭代器,当运行到这个语句的时候会保存当前的对象;下次再运行到这里的时候会接着上次的对象继续运行。
                yield c  
            else:
                break


def getDoc(request, id):
    """下载文件"""
    doc = get_object_or_404(Doc, id=id)

    update_to, filename = str(doc.file).split('/')  # 文件路径和名字
    # 获取文件的路径
    file_path = '%s/media/%s/%s' % (os.getcwd(), update_to, filename)
    print(filename)
    # 将下载文件分批次写入本地磁盘,先不将他们载入文件内存,读取文件,以512B为单位构建迭代器
    response = StreamingHttpResponse(read_file(file_path, 512))

    # 作为文件直接下载到本机,用户再用软件打开
    response['Content-Type'] = 'application/octet-stream'
    # 规定文件名的下载格式,在文件名为中文时,要加上escape_uri_path
    response['Content-Disposition'] = 'attachment; filename="{}"'.format(escape_uri_path(filename))
    return response

在这里,我们无论上传什么类型的文件,也无论文件名为中文或者其它数字、英文等都可以按原格式下载下来

 

 

 

 

你可能感兴趣的:(django开发)