首页 > 解决方案 > 在 DRF+Angular 中下载文件的问题

问题描述

我正在做有关 DRF+Angular 的项目。目前在本地主机上,我可以下载带有操作的文件:

    @action(methods=['get'], detail=True)
    def download(self, *args, **kwargs):
        instance = self.get_object()
        file_handle = instance.file.open()
        response = FileResponse(file_handle.read(), content_type='application/file')
        response['Content-Length'] = instance.file.size
        response['Content-Disposition'] = f'attachment; filename="{instance.file.name}"'    
        file_handle.close()
        return response

它适用于 localhost,但是当前端尝试在服务器上的相同 url 下获取相同的文件时 - 我会重定向到带有HTTP 401 Unauthorized. 但我已经输入了我的凭据。出了什么问题?

标签: pythondjangoangulardjango-rest-framework

解决方案


我认为前端交叉起源的问题你可以从这里阅读更多关于它的信息

同样在 django 你可以用django-cors-headers它来解决它我不能确定因为你没有提供你的网络服务器配置的完整细节

还要检查响应标头是否添加了带有文件类型的接受?

'Content-Description: File Transfer'
'Content-Type: application/octet-stream'
'Content-Disposition: attachment; filename="'.basename($file).'"'
'Content-Length: ' . filesize($file)
'Pragma: public'
'Cache-Control: must-revalidate'
'Expires: 0'
'Accept: <MIME_type>/*'

检查这个


推荐阅读