Django实现文件下载

7次阅读

共计 847 个字符,预计需要花费 3 分钟才能阅读完成。

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})

正文完
 0