2016-08-01 5 views
5

मुझे जेंजो रीस्ट फ्रेमवर्क प्रतिक्रिया के रूप में जेनरेट की गई फ़ाइल डाउनलोड को वापस करने की आवश्यकता है।Django REST Framework के साथ जेनरेट की गई फ़ाइल डाउनलोड कैसे करें?

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 

लेकिन यह json के रूप में एक msword दस्तावेज़ रिटर्न: मैं निम्नलिखित की कोशिश की।

मैं इसे कैसे बजाय फ़ाइल के रूप में डाउनलोड करना शुरू कर सकता हूँ?

+0

आप कहते हैं कि आप एक शब्द फ़ाइल जो आप इतना है कि मोर्चा के अंत उपयोगकर्ता फ़्रंट एंड को पास किए जाने बनाया है मतलब इसे डाउनलोड करने में सक्षम होना चाहिए? –

+0

@ PiyushS.Wanare बिल्कुल – Viktor

+0

शायद के बाद फ़ाइल उत्पन्न होता है, अगर यह आपके वेब सर्वर से सार्वजनिक रूप से सुलभ है (Django कोड, प्राधिकरण, आदि) के बिना आप एक 302 रीडायरेक्ट प्रतिक्रिया भेज सकते हैं। – Owen

उत्तर

1

उल्लेख मैं मीडिया फ़ोल्डर में फ़ाइल की बचत और सामने के अंत के लिए इसके बारे में लिंक का भेजकर मेरी समस्या हल।

@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 एसपीए)

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

यह आप के लिए काम कर सकते हैं:

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

return response. 

फ़्रंटएंड कोड के लिए this

+0

मैं इस लाइन 'yourFilePointer.write (प्रतिक्रिया, पाठ) ' नहीं मिलता है। मेरी फ़ाइल पहले ही जेनरेट की गई है और सर्वर पर सहेजी गई है। मुझे वहां 'पाठ' क्या लिखना चाहिए? – Viktor

+0

टेक्स्ट आपका शब्द फ़ाइल टेक्स्ट होगा। –

+0

जैसे हम टेक्स्ट फ़ाइल लिखते हैं जैसे 'f = open (' c: \ file.doc ', "w") f.write (टेक्स्ट) ' –