2017-02-10 42 views
2

路徑在我AngularJS/Python應用程序,我上傳使用dropzone一個文件,其中有這樣的物理路徑:地圖物理路徑,以服務爲下載

D:\uploadedFiles\tmpmj02zkex___5526310795850751687_n.jpg'

現在我想創建該文件的鏈接以在前端進行顯示和下載。鏈接看起來是這樣的:

http://127.0.0.1:8000/uploadedFiles/tmpmj02zkex___5526310795850751687_n.jpg

什麼是實現這一目標的最佳途徑?

回答

0

你可以簡單地添加一個url模式在例如。 urls.py

from django.conf.urls import url 
from . import views 

urlpatterns = [ 
    ..., 
    url(r'^uploadedFiles/(?P<file_name>.+)/$', views.download, name='download') 
] 

並且在例如所述控制器的download方法。 views.py建議在here

import os 
from django.conf import settings 
from django.http import HttpResponse 

# path to the upload dir 
UPLOAD_DIR = 'D:\uploadedFiles' 

... 

def download(request, file_name): 
    file_path = os.path.join(UPLOAD_DIR, file_name) 
    if os.path.exists(file_path): 
     with open(file_path, 'rb') as fh: 
      response = HttpResponse(fh.read(), content_type="application/octet-stream") 
      response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) 
      return response 
    else: 
     raise Http404 
+0

我們是否需要指定內容類型?上傳的文件可以是任何類型 –

+0

不,我們不這樣做,但推薦按照[在這裏]解釋(http://stackoverflow.com/questions/20392345/is-content-type-http-header-always -需要)。我已經更新了示例,因此無論文件類型如何,它總是強制用戶下載 –

+1

我必須將url模式更改爲'url(r'^ uploadedFiles /(?P [\ w \ - 。*] +)/ $ ',下載,名稱='下載'),'它工作。謝謝! –

相關問題