2016-04-03 85 views
7

我對使用Django很陌生,我試圖開發一個用戶可以上傳一些excel文件的網站,然後這些文件存儲在一個媒體文件夾中Webproject/project /媒體。Django下載文件

def upload(request): 
    if request.POST: 
     form = FileForm(request.POST, request.FILES) 
     if form.is_valid(): 
      form.save() 
      return render_to_response('project/upload_successful.html') 
    else: 
     form = FileForm() 
    args = {} 
    args.update(csrf(request)) 
    args['form'] = form 

    return render_to_response('project/create.html', args) 

該文件,然後顯示在列表中與他們上傳的任何其他文件,您可以點擊進入沿,它會顯示有關這些基本信息,他們已經上傳的excelfile的名稱。在這裏,我希望能夠下載同一再次使用鏈接excel文件:

<a href="/project/download"> Download Document </a> 

我的網址是

urlpatterns = [ 

       url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], 
              template_name="project/project.html")), 
       url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Post, template_name="project/post.html")), 
       url(r'^upload/$', upload), 
       url(r'^download/(?P<path>.*)$', serve, {'document root': settings.MEDIA_ROOT}), 

      ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

,但我得到的錯誤,服務()得到了一個意想不到的關鍵字參數「文檔根目錄'。誰能解釋如何解決這個問題?

OR

解釋我怎樣才能到要選擇的上傳文件,並使用服

def download(request): 
    file_name = #get the filename of desired excel file 
    path_to_file = #get the path of desired excel file 
    response = HttpResponse(mimetype='application/force-download') 
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) 
    response['X-Sendfile'] = smart_str(path_to_file) 
    return response 
+1

您能否包含'serve'視圖中的代碼? – xthestreams

回答

21

您參數文件_根下劃線錯過。但在生產中使用serve是個好主意。使用類似這樣的代碼:

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

def download(request, path): 
    file_path = os.path.join(settings.MEDIA_ROOT, path) 
    if os.path.exists(file_path): 
     with open(file_path, 'rb') as fh: 
      response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") 
      response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) 
      return response 
    raise Http404 
+0

工作很好。謝謝 – jsm1th

+0

它對我來說很順利。 thx @Sergey Gornostaev – gustav