加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Django下载文件

发布时间:2020-12-20 10:34:27 所属栏目:Python 来源:网络整理
导读:我是使用Django的新手,我正在尝试开发一个用户可以上传大量excel文件的网站,然后将这些文件存储在媒体文件夹Webproject / project / media中. def upload(request): if request.POST: form = FileForm(request.POST,request.FILES) if form.is_valid(): form
我是使用Django的新手,我正在尝试开发一个用户可以上传大量excel文件的网站,然后将这些文件存储在媒体文件夹Webproject / project / media中.

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)

然后,文档将与列表中的任何其他文档一起显示在列表中,您可以单击该文档,它将显示有关它们的基本信息以及它们已上载的文件的名称.从这里我希望能够使用以下链接再次下载相同的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)

但是我得到了错误,serve()得到了一个意外的关键字参数’document root’.谁能解释如何解决这个问题?

要么

说明如何使用上传的文件进行选择和提供

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

解决方法

您在参数document_root中错过了下划线.但是在生产中使用服务是个坏主意.使用这样的东西代替:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读