python - 如何在 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 从本地文件夹下载特定文件的问题?
解决方案
我有一个想法,最好将您的文件保存在静态或媒体文件夹中,并将媒体/静态 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>
推荐阅读
- c - 将 1 个数据帧合并到列表中的多个数据帧-R
- c# - WebApi Core 项目调试挂在 await client.GetAsync
- javascript - 如何在大屏幕上禁用 onclick 事件?
- python - 强制数组中非零元素之间的最小间距
- jquery - 无法从 Angular 中的 JQuery on() 方法访问全局变量
- sql-server - 无法加载新的数据事实表 SSIS
- dart - 如何正确启用/禁用 Flutter 的 Button
- reactjs - 意外令牌:生产构建中的运算符 (>)
- jquery - 在不刷新页面的情况下加载 Laravel 刀片
- php - 使用 xampp 在 system32 中的 .htaccess 和主机 URL“我创建”的问题