django提供下载服务;解决指定下载文件中文名不成功问题

一,django框架经常需要提供下载文件服务,这里描述下如何解决访问python接口下载文件。代码如下:

from django.http import FileResponse
from django.utils.encoding import escape_uri_path

'''获取文件二进制数据,并生成http-response对象'''
# 这里打开文件,并生成FileResonse文件对象。
file = open(target_dir , 'rb')
response = FileResponse(file)

'''定义新生成response的请求头'''
# 定义返回文件名称
file_name = name + '.' +doc_suffix
# 代表的是文件的形式传输的,这样做的好处是可以传输多种格式的文件,不管你是jpeg还是png都可以通过这种方式传送过去
response['Content-Type'] = 'application/octet-stream'
# 赋值中文title给下载数据
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file_name))

'''返回文件response对象'''
return response
# return JsonResponse({'data': "ok"}, safe=False)

二,解决无法定义文件名为中文问题

from django.utils.encoding import escape_uri_path

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

猜你喜欢

转载自blog.csdn.net/TFATS/article/details/105508476