Python Django下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36392510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:49:13  来源:igfitidea点击:

Django download a file

pythondjango

提问by Caroline

I'm quite new to using Django and I am trying to develop a website where the user is able to upload a number of excel files, these files are then stored in a media folder Webproject/project/media.

我对使用 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)

The document is then displayed in a list along with any other document they have uploaded, which you can click into and it will displays basic info about them and the name of the excelfile they have uploaded. From here I want to be able to download the same excel file again using the link:

然后该文档与他们上传的任何其他文档一起显示在列表中,您可以单击进入该列表,它将显示有关他们的基本信息以及他们上传的 excel 文件的名称。从这里我希望能够使用链接再次下载相同的 excel 文件:

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

My urls are

我的网址是

 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)

but I get the error, serve() got an unexpected keyword argument 'document root'. can anyone explain how to fix this?

但是我得到了错误,serve() 得到了一个意外的关键字参数“文档根”。谁能解释一下如何解决这个问题?

OR

或者

Explain how I can get the uploaded files to to be selected and served using

解释我如何让上传的文件被选择和使用

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

回答by Sergey Gornostaev

You missed underscore in argument document_root. But it's bad idea to use servein production. Use something like this instead:

您在参数文档_root 中遗漏了下划线。但是serve在生产中使用是个坏主意。使用类似这样的东西:

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

回答by Hasan Basri

You can add "download" attribute inside your tag to download files.

您可以在标签中添加“下载”属性来下载文件。

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

https://www.w3schools.com/tags/att_a_download.asp

https://www.w3schools.com/tags/att_a_download.asp

回答by Don Kirkby

I've found Django's FileFieldto be really helpful for letting users upload and download files. The Django documentation has a section on managing files. You can store some information about the file in a table, along with a FileFieldthat points to the file itself. Then you can list the available files by searching the table.

我发现 DjangoFileField对让用户上传和下载文件非常有帮助。Django 文档有一节是关于管理文件的。您可以在表中存储有关文件的一些信息,以及FileField指向文件本身的 。然后您可以通过搜索表格列出可用文件。

回答by Biswadp

Simple using html like this downloads the file mentioned using static keyword

像这样简单使用 html 下载使用 static 关键字提到的文件

<a href="{% static 'bt.docx' %}" class="btn btn-secondary px-4 py-2 btn-sm">Download CV</a>

回答by Devman

When you are you upload a file using FileField, the file will have a URL that you can use to point to the file and use HTML downloadattribute to download that file you can simply do this.

当您使用 上传文件时FileField,该文件将具有一个 URL,您可以使用该 URL 指向该文件并使用 HTMLdownload属性下载该文件,您只需执行此操作即可。

models.py

models.py

The model.py looks like this

model.py 看起来像这样

class CsvFile(models.Model):
    csv_file = models.FileField(upload_to='documents')

views.py

views.py

csv upload

csv上传

class CsvUploadView(generic.CreateView):

   model = CsvFile
   fields = ['csv_file']
   template_name = 'upload.html'

csv download

下载

class CsvDownloadView(generic.ListView):

    model = CsvFile
    fields = ['csv_file']
    template_name = 'download.html'

Then in your templates.

然后在你的模板中。

Upload template

上传模板

upload.html

upload.html

<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}
    <button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>

download template

下载模板

download.html

download.html

  {% for document in object_list %}

     <a href="{{ document.csv_file.url }}" download  class="btn btn-dark float-right">Download</a>

  {% endfor %}

I did not use forms, just rendered model but either way, FileFieldis there and it will work the same.

我没有使用表单,只是渲染模型,但无论哪种方式,FileField都在那里,它的工作原理是一样的。

回答by mananbh9

Reference:

参考

In view.py Implement function like,

在 view.py 中实现类似的功能,

def download(request, id):
    obj = your_model_name.objects.get(id=id)
    filename = obj.model_attribute_name.path
    response = FileResponse(open(filename, 'rb'))
    return response