zoukankan      html  css  js  c++  java
  • 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)) # 正确写法
  • 相关阅读:
    基于WS流的RTSP监控,H5低延时,Web无插件,手机,微信ONVIF操控摄像头方案
    H5微信视频,直播低延时,IOS限制全屏播放,自动播放问题处理。
    最新IOS,safari11中对webrtc支持,IOS和android视频聊天,web低延时视频教学技术分析
    MySql 用户篇
    Sql Server 数据库帮助类
    [C#基础知识]转载 private、protected、public和internal的区别
    Mysql 插入语句
    .net core identityserver4 学习日志
    mysql 事务模板
    .net core 生成二维码
  • 原文地址:https://www.cnblogs.com/crystaltu/p/9228448.html
Copyright © 2011-2022 走看看