Django文件下载函数代码

def download_user_record_excel(request):
    req_params = request.GET
    logger_request(req_params)
    try:
        start_date = req_params.get('start_date')
        end_date = req_params.get('end_date')
        excel_name = str(start_date) + "至" + 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中的path。
        response["Content-Disposition"] = "attachment; filename*=UTF-8''{}".format(escape_uri_path(excel_name))
        return response
    except Exception as e:
        logger_error(e)
        data = e.__str__()
        context = FAIL_CONTEXT
        context['data'] = data
        return JsonResponse(context, json_dumps_params={'ensure_ascii': False})
Scroll Up