flask发送文件和Unicode文件名:在IE中出现问题

2024-10-05 14:22:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个函数,可以动态生成一些csv文件并发送给用户下载。在

代码如下:

@app.route('/survey/<survey_id>/report')
def survey_downloadreport(survey_id):  
    survey, bsonobj = survey_get(survey_id)
    resps = response_get_multi(survey_id)

    fields = ["_id", "sid", "date", "user_ip"]
    fields.extend(survey.formfields)    

    csvf = StringIO.StringIO()
    wr = csv.DictWriter(csvf, fields, encoding = 'cp949')
    wr.writerow(dict(zip(fields, fields)))
    for resp in resps :
        wr.writerow(resp)

    csvf.seek(0)

    now = datetime.datetime.now()
    report_name = survey.name + "(" + \
                  now.strftime("%Y-%m-%d-%H:%M:%S") +\
                  ")" + ".csv"

    report_name = report_name.encode("utf-8")



    return send_file(csvf,
                 as_attachment = True,
                 attachment_filename = report_name)

如您所见,文件名从unicode转换为字符串,并使用utf-8(确切地说,它们是韩语字母)

问题是,在IE中查看页面时,文件名会完全中断(在chrome中没有问题)。在

似乎需要编辑头来匹配不同浏览器的解析规则,但我不知道如何在flask中实现这一点。在


Tags: csvnamereportidfieldsgetdatetimewr
2条回答

使用Content-Disposition: attachment; filename="..."来设置下载文件的名称(这正是Flask的send_file所做的)对于非ASCII字符是不可靠的。在

除非Flask使用的werkzeug.http库中支持rfc5987,并且在所有您想要瞄准的浏览器中,这都是不可修复的。在

同时,一种更可靠的跨浏览器方法是,当您链接到URI时,将UTF-8-URL编码的文件名放在URI的后面部分,即:

IRI path: /survey/1/report/안녕.csv
URI path: /survey/1/report/%ec%95%88%eb%85%95.csv

背景请参见How to encode UTF8 filename for HTTP headers? (Python, Django)。在

尝试添加

mimetype = 'text/csv; charset=x-EBCDIC-KoreanAndKoreanExtended'

发送_文件。在

相关问题 更多 >