python - 在 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
. 但我已经输入了我的凭据。出了什么问题?
解决方案
我认为前端交叉起源的问题你可以从这里阅读更多关于它的信息
同样在 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>/*'
检查这个
推荐阅读
- javascript - useState 有时有效但有时无效的奇怪情况
- c - 是什么导致 realloc() 无效的下一个大小错误?
- c# - 每个导航属性一个类
- bash - 在 for 循环中递增到下一个文件
- android - Android 用例和存储库单元测试
- javascript - 如何在 htmlService 中附加新内容而不调用 x 时间返回(gs 代码)
- java - 我正在从 onClickListener 中删除一个方法并单独调用它,然后它会导致问题
- memory - 为什么默认的“ulimit”值这么低
- r - 序列日期和数据框
- python - 查找行之间的绝对差异并将差异与其他行进行比较