首页 > 解决方案 > 尝试使用 Django-Rest-Framework 下载 excel 文件时获取 unicode 字符作为响应

问题描述

我正在开发应用程序,我需要在使用 react 单击下载按钮时下载保存在项目媒体目录中的 excel 文件。我已经为它编写了一个 api,从我找到的答案中使用 django rest 框架下载文件,但邮递员给了我一个 unicode 字符的响应。 邮递员的回应

这是我的 DRF 观点:

def download(self):
    file_name= 'reports.xlsx'
    file_path = (settings.MEDIA_ROOT +'/'+ file_name).replace('\\', '/')
    file_wrapper = FileWrapper(open(file_path,'rb'))
    file_mimetype = mimetypes.guess_type(file_path)
    response = HttpResponse(file_wrapper, content_type=file_mimetype )
    response['X-Sendfile'] = file_path
    response['Content-Length'] = os.stat(file_path).st_size
    response['Content-Disposition'] = 'attachment; filename=%s' % str(file_name) 

    return response

如果有人可以帮助我解决它,我将不胜感激。谢谢!

标签: djangodjango-rest-frameworkdjango-viewspostmandjango-urls

解决方案


推荐阅读