简体   繁体   English

Django下载文件

[英]Django download files

I'm working in a project which I want display many images in a website, so the user can download them.我正在一个项目中工作,我希望在网站上显示许多图像,以便用户可以下载它们。 I can display the name of the images, but the download isn't working.我可以显示图像的名称,但下载不起作用。 I think it's something on my views, because I'm using Django, and getting the error the current path ... didn't match any of this .我认为这是我的观点,因为我正在使用 Django,并且the current path ... didn't match any of this得到错误the current path ... didn't match any of this The name of the directory with the images is Images , and has others sub directories inside, and inside those sub directories, there are the images.包含图像的目录的名称是Images ,里面有其他子目录,在这些子目录中,有图像。

My views page, I think the problem is here, in the download function:我的views页面,我觉得问题出在这里,在下载功能里:

from django.shortcuts import render
import os
from django.http import HttpResponse, Http404
from django.http import FileResponse

def index(request):
    flPath = os.listdir('Images/')
    fl4 = []
    for root, dirs, files in os.walk("Images/", topdown=False):
        for name in files:
            fl4.append(os.path.join(root, name))
        for name in dirs:
            fl4.append(os.path.join(root, name))
    return render(request, 'catalog/index.html', {'path': fl4})

def downloadImage(request, path):
    imagePath = 'Images/'
    file_path = os.path.join(imagePath, path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type='text/csv')
            response['Content-Disposition'] = 'inline; filename=' + file_path
            return response
    raise Http404

My app urls, catalog.urls:我的应用程序网址,catalog.urls:

from django.urls import path, include
from .views import *
urlpatterns = [
    path('', index, name='index'),
    path('Images/<str:path>', downloadImage, name='download'),
]

My project urls, SiteSmu4Img:我的项目网址,SiteSmu4Img:

from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls),
    path('Images/', include('catalog.urls')),
    path('', include('catalog.urls')),
]

My index.html:我的 index.html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% if path %}
    <table>
        <tr>
            <th>Images</th>
            <th>Download</th>
        </tr>
        {% for i in path %}
            <tr>
                <td>{{ i }}</td>
                <td><a href="{{ i }}">download</a></td>
            </tr>
        <img src="Images/{{ i }}">
        {% endfor %}
    </table>
{% endif %}
</body>
</html>

The stack trace:堆栈跟踪:

[03/Nov/2020 17:11:39] "GET / HTTP/1.1" 200 3508
Not Found: /Images/Images/Images/fisc/LOGO NOVA.png
Not Found: /Images/Images/Images/leg/Niterói.jpg
[03/Nov/2020 17:11:39] "GET /Images/Images/Images/fisc/LOGO%20NOVA.png HTTP/1.1" 404 2787
[03/Nov/2020 17:11:39] "GET /Images/Images/Images/leg/Niter%C3%B3i.jpg HTTP/1.1" 404 2783
Not Found: /Images/Images/Images/leg/thumb_drone_site@2x.png
Not Found: /Images/Images/Images/urb/teste/1461270191180.jpg
[03/Nov/2020 17:11:39] "GET /Images/Images/Images/leg/thumb_drone_site@2x.png HTTP/1.1" 404 2812
[03/Nov/2020 17:11:39] "GET /Images/Images/Images/urb/teste/1461270191180.jpg HTTP/1.1" 404 2812
Not Found: /Images/Images/Images/urb/teste/1461270191336.jpg
[03/Nov/2020 17:11:39] "GET /Images/Images/Images/urb/teste/1461270191336.jpg HTTP/1.1" 404 2812
Not Found: /Images/Images/Images/urb/teste/1461270202199.jpg
[03/Nov/2020 17:11:39] "GET /Images/Images/Images/urb/teste/1461270202199.jpg HTTP/1.1" 404 2812
Not Found: /Images/Images/Images/urb/teste
[03/Nov/2020 17:11:39] "GET /Images/Images/Images/urb/teste HTTP/1.1" 404 2758
Internal Server Error: /Images/Images/Images/urb
Traceback (most recent call last):
  File "C:\Users\Documentos\SiteSmu4_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Documentos\SiteSmu4_env\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Documentos\SiteSmu4_env\SiteSmu4Img\catalog\views.py", line 20, in downloadImage
    with open(file_path, 'rb') as fh:
PermissionError: [Errno 13] Permission denied: 'Images/urb'
Internal Server Error: /Images/Images/Images/fisc
Traceback (most recent call last):
  File "C:\Users\Documentos\SiteSmu4_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Documentos\SiteSmu4_env\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Documentos\SiteSmu4_env\SiteSmu4Img\catalog\views.py", line 20, in downloadImage
    with open(file_path, 'rb') as fh:
PermissionError: [Errno 13] Permission denied: 'Images/fisc'
[03/Nov/2020 17:11:40] "GET /Images/Images/Images/urb HTTP/1.1" 500 66812
[03/Nov/2020 17:11:40] "GET /Images/Images/Images/fisc HTTP/1.1" 500 66828
Not Found: /Images/Images/Images/urb/1461270202199.jpg
[03/Nov/2020 17:11:40] "GET /Images/Images/Images/urb/1461270202199.jpg HTTP/1.1" 404 2794
Internal Server Error: /Images/Images/Images/leg
Traceback (most recent call last):
  File "C:\Users\Documentos\SiteSmu4_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Documentos\SiteSmu4_env\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Documentos\SiteSmu4_env\SiteSmu4Img\catalog\views.py", line 20, in downloadImage
    with open(file_path, 'rb') as fh:
PermissionError: [Errno 13] Permission denied: 'Images/leg'
[03/Nov/2020 17:11:40] "GET /Images/Images/Images/leg HTTP/1.1" 500 66812
Not Found: /Images/Images/Images/urb/LOGOFOOTER@2x.jpg
[03/Nov/2020 17:11:40] "GET /Images/Images/Images/urb/LOGOFOOTER@2x.jpg HTTP/1.1" 404 2794
Not Found: /Images/Images/Images/urb/x22323604_NI-Niteroi-RJ-26-05-2010Acessibilidade-em-Niteroi-Deficientes-fi.jpg.pagespeed.ic.KEumjIi-TY.jpg
[03/Nov/2020 17:11:40] "GET /Images/Images/Images/urb/x22323604_NI-Niteroi-RJ-26-05-2010Acessibilidade-em-Niteroi-Deficientes-fi.jpg.pagespeed.ic.KEumjIi-TY.jpg HTTP/1.1" 404 3061
Not Found: /Images/leg/thumb_drone_site@2x.png
[03/Nov/2020 17:11:43] "GET /Images/leg/thumb_drone_site@2x.png HTTP/1.1" 404 2770

The issue in you code is:您代码中的问题是:
catalog.urls: path('Images/', include('catalog.urls')), catalog.urls: path('Images/', include('catalog.urls')),

SiteSmu4Img: path('Images/<str:path>', downloadImage, name='download'), SiteSmu4Img: path('Images/<str:path>', downloadImage, name='download'),

so, in total the path should be like Images/Images/<str:path> , but in the template you have just:所以,总的来说,路径应该像Images/Images/<str:path> ,但在模板中你只有:
<img src="Images/{{ i }}">

Correct this issue first, then show the stacktrace if the solution won't fix all the errors.首先更正此问题,然后在解决方案无法修复所有错误时显示堆栈跟踪。

Add another Images into the template for the beginning and add the leading slash in the path:在模板中添加另一个Images作为开头,并在路径中添加前导斜杠:

<img src="/Images/Images/{{ i }}">

you can't get images or any static file directly.您无法直接获取图像或任何静态文件。

Django finds resources of the static folder or media folder. Django 查找静态文件夹或媒体文件夹的资源。

add images in static folder and add STATIC_FOLDER , STATIC_URL values in settings.py在静态文件夹中添加图像并在 settings.py 中添加STATIC_FOLDERSTATIC_URL

if you want to add images through the website, set MEDIA_ROOT , MEDIA_URL in settings.py如果要通过网站添加图片, MEDIA_URLsettings.py设置MEDIA_ROOTMEDIA_URL

add a URL in urls.py .urls.py添加一个 URL。 now you can access images through Django.现在您可以通过 Django 访问图像。

get Media files Access 获取媒体文件访问权限

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM