【问题标题】:Django response send file as well as some text dataDjango 响应发送文件以及一些文本数据
【发布时间】:2020-03-03 20:32:19
【问题描述】:

目前我从我的 Django-Rest 控制器发送一个 zip 文件作为响应,该 zip 文件将在前端下载,此功能工作正常,但现在我想发送一些数据以及 zip 文件回复,有什么办法吗?

这是我的 Django-REST 控制器代码

response = HttpResponse(byte_io.getvalue(),content_type='application/x-zip-compressed')

response['Content-Disposition'] = f'attachment;filename{my-sample-zip-file}'

return response

如何在前端使用此 zip 文件发送一些数据?

【问题讨论】:

    标签: django-rest-framework download python-3.6 response django-2.0


    【解决方案1】:

    您可以使用 django 的 HTTP 请求响应模块来完成。 参考:https://docs.djangoproject.com/en/2.2/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment

    如果您想像代码一样在生产环境中执行此操作,您可能还想处理文件不可用的情况,设置错误并返回整洁。另外,最好把它放在一个通用文件中,然后像下面这样定义 download_file:

    from common_library import FileResponse
    from django.http import JsonResponse
    
        def download_file( self ):
        if self.error_response:
            response = JsonResponse( { "error" : self.error_response } ) 
        else:    
            response = FileResponse(self.report_file_abs_path,  self.report_filename)
            response['Content-Type'] = 'application/xlsx'
            response['Content-Disposition'] = 'attachment; filename=' + self.report_filename
        return response
    

    注意:FileResponse 是一个用户定义的包装函数,您可以定义它。

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      相关资源
      最近更新 更多