django 下载文件 无法正常打开

下载文件,无法正常打开,如下图

clipboard.png

需手动加后缀名修改文件格式方可正常打开
进而能得知文件内容正常
如下图,给“下载”文件加上后缀即可得到正常下载的内容

clipboard.png

问题整理:(此下载功能采用StreamHttpResponse)

1、已在源码中指定了下载的文件名:

response['Content-Disposition'] = 'attachment;filename="{f_name}"'.format(f_name=the_file_name)

 

但结果下载的文件统一均为“下载”的文件名字

2、下载功能和数据内容是正常的,应该是命名这个环节出错,并且文件是含有中文字符请帮指正。

补充:
python版本 3.6
django版本 1.11.13

 

打开网页检查,如下图

clipboard.png

发现是Content-Disposition出错

接下来,就针对这个属性在网上搜集资料,解决步骤如下:

1、导入模块

from django.utils.encoding import escape_uri_path

 

2、重写该属性

response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(the_file_name))

 




注:其中BUG1和BUG2普通解决方案不是最佳解决途径

from django.http import StreamingHttpResponse

# 切片读取文件
def file_iterator(filename,chunk_size=512):
    with open(filename,'rb') as f:
        while True:
            c=f.read(chunk_size)
            if c:
                yield c
            else:
                break

# 下载功能
def download_file(request):
    the_file_name = models.FileObj.objects.get(id=request.GET.get("id")).fileName  # 显示在弹出对话框中的默认的下载文件名
    print(the_file_name)
    file_path = os.path.join(file_dir,the_file_name) # 要下载的文件路径
    response = StreamingHttpResponse(file_iterator(file_path))
    response['Content-Type'] = 'application/octet-stream' # #设定文件头,这种设定可以让任意文件都能正确下载,而且已知文本文件不是本地打开
    # response['Content-Disposition'] = 'attachment;filename="download.zip"' # BUG1:给出一个固定的文件名,且不能为中文,文件名写死了
    # response['Content-Disposition'] = 'attachment;filename={0}'.format(the_file_name.encode("utf-8")) # BUG2:中文会乱码
    response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(the_file_name)) # 正确写法

 

posted @ 2018-06-26 11:59  Nullnullisnull  阅读(1290)  评论(1编辑  收藏  举报