2016-11-10 93 views
0

我創建了一個鏈接,當用戶按下它時,它將從Django的media文件夾下載pdf文件到用戶機器。用Django中的FileField從HTML文件中的HTTP鏈接下載文件

我嘗試了不同的方法,但對我來說都是錯誤的。它告訴我文件找不到,或者代碼正在運行,但文件已損壞。

我的HTML鏈接:

<td> <a href="/download/">Download</a></td> 

我的URL模式連接到一個觀點:

url(r'^download/$', views.DownloadPdf), 

我的FileField是這樣的:

​​

以下代碼片段認爲,下載已損壞的pdf:

def DownloadPdf(request): 

filename = '/home/USER/PycharmProjects/MyProject/media/Invoice_Template.pdf' 
response = HttpResponse(content_type='application/pdf') 
fileformat = "pdf" 
response['Content-Disposition'] = 'attachment; 
filename=thisismypdf'.format(fileformat) 
return response 

那麼,我必須做些什麼才能使它工作?

+0

你應該爲你的'media'文件夾你的網絡服務器。在開發中,開發服務器將完成這項任務。詳情請閱讀https://docs.djangoproject.com/en/1.10/howto/static-files/。 –

回答

0
with open(os.path.join(settings.MEDIA_ROOT, 'Invoice_Template.pdf'), 'rb') as fh: 
    response = HttpResponse(fh.read(), content_type="application/pdf") 
    response['Content-Disposition'] = 'attachment; filename=invoice.pdf' 
    return response 
+0

這將整個事件讀入內存,最好使用FileResponse或讓Web服務器句柄發送它。 – RemcoGerlich

+0

@RemcoGerlich是的,你說得對,但我認爲Vaios Lk一開始就必須理解簡單的東西。 –

0

@Sergey Gornostaev的代碼只是工作完美,但我後下我的代碼,因爲它是在一個differect方式的形式給出。

我糾正一點點我的代碼:

def DownloadPdf(request): 
    path_to_file = '/home/USER/PycharmProjects/MyProject/media /Invoice_Template.pdf' 
    f = open(path_to_file, 'r') 
    myfile = File(f) 
    response = HttpResponse(myfile, content_type='application/pdf') 
    response['Content-Disposition'] = 'attachment; filename=filename' 
    return response 

但只有在PDF文件(可與txt文件)給我的錯誤:

'utf-8' codec can't decode byte 0xe2 in position 10

+0

由於您以文本形式打開文件,但pdf是二進制文件。在'open'中將'r'改爲'rb'。 –

+0

也適用!幫助我瞭解這一切。 thnx人。 –