【问题标题】:Problem with downloading file in DRF+Angular在 DRF+Angular 中下载文件的问题
【发布时间】:2019-03-29 17:21:14
【问题描述】:

我正在做有关 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 的 DRF 模板。但我已经输入了我的凭据。出了什么问题?

【问题讨论】:

  • 你解决了吗?

标签: python django angular django-rest-framework


【解决方案1】:

我认为前端跨域的问题 你可以从here了解更多信息

你也可以在 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>/*'

查看this

【讨论】:

  • 抱歉,请阅读您的留言。据我所知,CORS 已经被使用了——除了这个文件下载之外,Django-Angular 通信没有任何其他问题。如果我直接向 DRF api admin 提供凭据,它就可以工作 - 然后我可以下载文件。看起来像一些标题问题。
  • 你能检查这些响应头吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2012-04-18
  • 1970-01-01
  • 2019-03-16
  • 2020-11-24
  • 2017-11-10
相关资源
最近更新 更多