2016-08-01 15 views
5

Tôi cần trả lại tệp đã tải xuống dưới dạng phản hồi khung REST của Django. Tôi đã thử các cách sau:Làm thế nào để trả về tải xuống tệp được tạo bằng khung công tác REST Django?

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 

Nhưng nó trả về tài liệu msword là json.

Làm cách nào để bắt đầu tải xuống dưới dạng tệp?

+0

Bạn có nghĩa là để nói rằng bạn đã tạo ra một file word mà bạn cần phải vượt qua để Front End để người dùng cuối Mặt trận có thể tải xuống không? –

+0

@ PiyushS.Wanare chính xác – Viktor

+0

Có thể sau khi tệp được tạo, nếu có thể truy cập công khai từ máy chủ web của bạn (không có mã Django, ủy quyền, v.v.), bạn có thể gửi phản hồi Chuyển hướng 302. – Owen

Trả lời

1

tôi giải quyết vấn đề của tôi bằng cách tiết kiệm tập tin trong thư mục phương tiện truyền thông và gửi liên kết của nó để 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) 

Và xử lý này như thế nào trong front-end của tôi (AngularJS SPA)

$http(req).success(function (url) { 
    console.log(url); 
    window.location = url; 
}) 
2

Điều này có thể làm việc cho bạn:

file_path = file_url 
FilePointer = open(file_path,"r") 
response = HttpResponse(FilePointer,content_type='application/msword') 
response['Content-Disposition'] = 'attachment; filename=NameOfFile' 

return response. 

Đối với mã FrontEnd tham khảo this

+0

Tôi không nhận được dòng này 'yourFilePointer.write (câu trả lời, văn bản) '. Tệp của tôi đã được tạo và lưu trên máy chủ. Tôi nên viết 'văn bản' nào? – Viktor

+0

Văn bản sẽ là văn bản tệp từ của bạn. –

+0

khi chúng tôi viết tệp văn bản như 'f = open ('c: \ file.doc'," w ") f.write (văn bản)' –

Các vấn đề liên quan