2012-11-30 16 views
0

文件入門禁止我有這樣的代碼同時下載在Django視圖

class DownloadView(TemplateView): 
    template_name = 'pdfform/create_form2.html' 


    def serve_pdf(self, request): 
     #pdf_data = magically_create_pdf() 

     response = HttpResponse(mimetype='application/pdf') 
     response['Content-Disposition'] = 'attachment; filename="http://localhost/static/pdfs/angular.pdf"' 
     return response 

當我去到該頁面我得到立即下載對話框,但我無法下載該文件。它說,

http 403 forbidden 

現在我可以直接訪問該文件,但把http://localhost/static/pdfs/angular.pdf在瀏覽器的

我TREID puting static/pdfs/angular.pdf但同樣的錯誤

+0

我認爲這個頁面可能是有用的:http://stackoverflow.com/questions/1156246/having-django-serve-downloadable-files –

回答

0

文件名中應該只是一個普通的文件名,而不是http://...

因此改變

response['Content-Disposition'] = 'attachment; filename="http://localhost/static/pdfs/angular.pdf"' 

response['Content-Disposition'] = 'attachment; filename="angular.pdf"' 

此外,您還需要通過響應提供服務的文件內容,以便該文件的內容供應。

... 
def serve_pdf(self, request): 
    from django.core.servers.basehttp import FileWrapper 
    # your code 

    wrapper  = FileWrapper(open(your_pdf_file_path)) 
    response  = HttpResponse(wrapper,'application/pdf') 
    response['Content-Length']  = os.path.getsize(your_pdf_file_path)  
    response['Content-Disposition'] = 'attachment; filename="angular.pdf"' 
    return response 
+0

但怎樣讓系統發現文件名 – user825904

+0

@ user32 ...什麼? –

+0

@ user32,檢查更新後的答案,您需要打開pdf文件並更新'response'對象以發送其數據。 – Rohan