Django响应发送文件以及一些文本数据

问题描述 投票:0回答:1

目前,我从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个回答
0
投票

您可以使用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是您可以定义的用户定义的包装函数。

© www.soinside.com 2019 - 2024. All rights reserved.