django 下载文件,指定文件中文名称

Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。
Content-disposition其实可以控制用户请求所得的内容存为一个文件的时候提供一个默认的文件名,文件直接在浏览器上显示或者在访问时弹出文件下载对话框。
Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名。

import os,sys
from django.http import StreamingHttpResponse
from django.utils.encoding import escape_uri_path


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

def extractfile(request):
    filepath="/".join(os.path.dirname(os.path.abspath(__file__)).split("/")[:-1])+"/files"
    the_file_name = filepath+"/Kafka权威指南.pdf"
    response = StreamingHttpResponse(file_iterator(the_file_name))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(escape_uri_path('Kafka权威指南.pdf'))

    return response

参考;

https://segmentfault.com/q/1010000009078463

https://www.jianshu.com/p/4c52cb691f54

https://cloud.tencent.com/developer/article/1365795

原文地址:https://www.cnblogs.com/sea-stream/p/11524224.html