首页 > 解决方案 > 如何在 Django 中为 zip 文件创建可下载的 URL?

问题描述

我正在尝试创建一个网页,该网页具有一个表格,该表格中的一列下载驻留在我的计算机中的特定文件。应该下载的文件基于该行的 ID 号。(ID 是我表中的一列)

前任。如果用户单击第 3 行中的 URL,则应下载本地文件中名为“3.zip”的文件。

我已经<a href="<path>" download>在我的 HTML 模板文件中尝试过,但我意识到在 Django 中方法是不同的。然后我使用 HTTPResponse 作为附件方法。

这是我的 Views.py 下载代码。

def download_file(request):
    fl_path = '/home/harish/Desktop/cvision/users_output_files/5/5.zip'
    filename = '5.zip'

    with open(fl_path, 'r') as zip_file:
        response = HttpResponse(zip_file, content_type='application/force-download')
        response['Content-Disposition'] = 'attachment; filename="%s"'%filename
        return response

网址.py

urlpatterns = [
    path('',views.homepage),
    path('add',views.datapage),
    path('newdata',views.newdata),
    path('newuser',views.newuser),
    path('download_file/',views.download_file)
]

所以,当我去路径http://127.0.0.1:8000/download_file时,文件应该被下载。但相反,我得到了一个错误。

'utf-8' codec can't decode byte 0xeb in position 10: invalid continuation byte

如果我们忽略编码错误,我该如何解决根据该行的 ID 从本地文件夹下载特定文件的问题?

标签: pythondjangourl

解决方案


我有一个想法,最好将您的文件保存在静态或媒体文件夹中,并将媒体/静态 url 根设置添加到您的 urls.py 文件中

设置.py

 # Base url to serve media files
MEDIA_URL = '/media/'

# Path where media is stored
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

网址.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    ...
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

最后你可以在 django 模板中为你提供文件,链接如下

<a href="{{ STATIC_URL }}/files/somefile"> download</a>

或者

<a href="{{ MEDIA_URL }}/files/somefile"> download</a>

推荐阅读