本文介绍了如何使用Django REST Framework返回生成的文件下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将生成的文件下载作为Django REST框架响应返回.我尝试了以下方法:
I need to return generated file download as a Django REST Framework response. I tried the following:
def retrieve(self, request, *args, **kwargs):
template = webodt.ODFTemplate('test.odt')
queryset = Pupils.objects.get(id=kwargs['pk'])
serializer = StudentSerializer(queryset)
context = dict(serializer.data)
document = template.render(Context(context))
doc = converter().convert(document, format='doc')
res = HttpResponse(
FileWrapper(doc),
content_type='application/msword'
)
res['Content-Disposition'] = u'attachment; filename="%s_%s.zip"' % (context[u'surname'], context[u'name'])
return res
但是它返回一个msword文档为 json
.
But it returns a msword document as json
.
如何使它开始以文件形式下载?
How do I make it start downloading as file instead?
推荐答案
我通过将文件保存在媒体文件夹中并将其链接发送到前端来解决了我的问题.
I solved my problem by saving file in media folder and sending of the link of it to front-end.
@permission_classes((permissions.IsAdminUser,))
class StudentDocxViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
def retrieve(self, request, *args, **kwargs):
template = webodt.ODFTemplate('test.odt')
queryset = Pupils.objects.get(id=kwargs['pk'])
serializer = StudentSerializer(queryset)
context = dict(serializer.data)
document = template.render(Context(context))
doc = converter().convert(document, format='doc')
p = u'docs/cards/%s/%s_%s.doc' % (datetime.now().date(), context[u'surname'], context[u'name'])
path = default_storage.save(p, doc)
return response.Response(u'/media/' + path)
就像在我的前端(AngularJS SPA)中一样处理
And handled this like in my front-end (AngularJS SPA)
$http(req).success(function (url) {
console.log(url);
window.location = url;
})
这篇关于如何使用Django REST Framework返回生成的文件下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!