刚刚写好的下载文件测试时用的英文没有问题,结果提交后别人用了后说不能用
我看了下就是中文编码造成的,解决办法也很简单
response['Content-Disposition'] = 'attachment;filename="%s"' % filename
改成
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(filename)) return
完整代码
import logging
logger = logging.getLogger('huashengxiaodian')
def download(request, file=''):
if file:
filename = file
else:
filename = request.GET.get('file')
file_path = os.path.join('static/file_upload/', filename)
logger.info(file_path)
if not os.path.isfile(file_path): # 判断下载文件是否存在
return HttpResponse("参数错误,请联系管理员")
def file_iterator(file_path, chunk_size=2048*1024):
"""
文件生成器,防止文件过大,导致内存溢出
:param file_path: 文件绝对路径
:param chunk_size: 块大小
:return: 生成器
"""
iii =0
with open(file_path, mode='rb') as f:
while True:
file_size = os.path.getsize(file_path)
logger.info(file_size/float(1024*1024))
logger.info('读取文件大小')
logger.info(file_size/chunk_size)
iii = iii+1
logger.info(chunk_size*iii/float(1024*1024))
c = f.read(chunk_size)
if c:
yield c
else:
print(c)
break
try:
# 设置响应头
# StreamingHttpResponse将文件内容进行流式传输,数据量大可以za AXDEWQ用这个方法
response = StreamingHttpResponse(file_iterator(file_path))
# 以流的形式下载文件,这样可以实现任意格式的文件下载
response['Content-Type'] = 'application/octet-stream'
# Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(filename)) # 文件名可设置为中文
logger.info(response)
except:
return HttpResponse("参数错误,请联系管理员")
return response