当前位置: 首页 > 后端技术 > Python

Django实现文件下载

时间:2023-03-26 15:14:36 Python

defdownload_user_record_excel(request):req_params=request.GETlogger_request(req_params)尝试:start_date=req_params.get('start_date')end_date=req_params.get('end_date')excel_name=str(start_date)+"to"+str(end_date)+"用户使用记录.xlsx"excel_path_name='./report/{}'.format(excel_name)save_user_record_to_excel(start_date,end_date,excel_path_name)file=open(excel_path_name,'rb')response=FileResponse(file)response['Content-Type']='application/octet-stream'#这里要注意,网上找的方法都是response['Content-Disposition']='attachment;filename="filename.py"',#但如果文件名是英文,就没有问题。如果文件名包含中文,则下载的文件名将更改为url中的路径。response["Content-Disposition"]="attachment;filename*=UTF-8''{}".format(escape_uri_path(excel_name))returnresponseexceptexceptionase:logger_error(e)data=e.__str__()上下文=FAIL_CONTEXT上下文['数据']=datareturnJsonResponse(context,json_dumps_params={'ensure_ascii':False})