提供django中要下载的文件的路径

发布于 2025-01-11 08:13:05 字数 2879 浏览 0 评论 0原文

视图.py

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/pdf")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    raise Http404

urls.py

from unicodedata import name
from django.urls import path
from Profile import views

urlpatterns = [
  ...
  path('download/<str:path>/', views.download, name="download"),
]

模型.py

from django.db import models
from django.contrib.auth.models import User
from taggit.managers import TaggableManager

# Create your models here.
class ProfileModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(null=True)
    address = models.CharField(max_length=255 , null=True)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return str(self.user)

模板

{% extends 'base.html' %}

{% block content %}
Welcome, {{request.user.username}}
<table>
    <tr>
        <th>First Name: </th>
        <th>{{user.first_name}}</th>
    </tr>
    <tr>
        <th>Last Name: </th>
        <th>{{user.last_name}}</th>
    </tr>
    <tr>
        <th>Email: </th>
        <th>{{user.email}}</th>
    </tr>
    <tr>
        <th>Image: </th>
        {% if user.image %}
        <!-- here is the error -->
        <th><a href="{% url 'download' user.image.url%}"><img src=" {{user.image.url}}" alt="IMage...." style="object-fit: cover;
            border-radius: 50%;
            height: 200px;
            width: 200px;"></a></th>
        {% endif %}
    </tr>
    <tr>
        <th>Address: </th>
        <th>{{user.address}}</th>
    </tr>
    <tr>
        <th>Bio: </th>
        <th>{{user.bio|linebreaks}}</th>
    </tr>
</table>

MEDIA_URL = '/images/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')

问题在于我为模板中要下载的文件提供的路径。我不知道将文件所需路径提供给下载视图的正确方法。 错误 - “未找到带有参数 '('/images/Nitro_Wallpaper_5000x2813_Vm2jvWw.jpg',)' 的反向'下载'。尝试了 1 个模式:['Profile/download/(?P[^/]+)/\ Z']”。 但“Nitro_Wallpaper_5000x2813_Vm2jvWw.jpg”存在于我的图像文件夹中。

views.py

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/pdf")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    raise Http404

urls.py

from unicodedata import name
from django.urls import path
from Profile import views

urlpatterns = [
  ...
  path('download/<str:path>/', views.download, name="download"),
]

models.py

from django.db import models
from django.contrib.auth.models import User
from taggit.managers import TaggableManager

# Create your models here.
class ProfileModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(null=True)
    address = models.CharField(max_length=255 , null=True)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return str(self.user)

template

{% extends 'base.html' %}

{% block content %}
Welcome, {{request.user.username}}
<table>
    <tr>
        <th>First Name: </th>
        <th>{{user.first_name}}</th>
    </tr>
    <tr>
        <th>Last Name: </th>
        <th>{{user.last_name}}</th>
    </tr>
    <tr>
        <th>Email: </th>
        <th>{{user.email}}</th>
    </tr>
    <tr>
        <th>Image: </th>
        {% if user.image %}
        <!-- here is the error -->
        <th><a href="{% url 'download' user.image.url%}"><img src=" {{user.image.url}}" alt="IMage...." style="object-fit: cover;
            border-radius: 50%;
            height: 200px;
            width: 200px;"></a></th>
        {% endif %}
    </tr>
    <tr>
        <th>Address: </th>
        <th>{{user.address}}</th>
    </tr>
    <tr>
        <th>Bio: </th>
        <th>{{user.bio|linebreaks}}</th>
    </tr>
</table>

MEDIA_URL = '/images/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')

The problem is with the path I have provided for the file to be downloaded in the template. I don't know the correct way to give the required path of the file to the download view.
Error - "Reverse for 'download' with arguments '('/images/Nitro_Wallpaper_5000x2813_Vm2jvWw.jpg',)' not found. 1 pattern(s) tried: ['Profile/download/(?P[^/]+)/\Z']".
But "Nitro_Wallpaper_5000x2813_Vm2jvWw.jpg" is present in my images folder.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮生未歇 2025-01-18 08:13:05

视图.py

def download(request, filename):
    path = os.path.join(settings.MEDIA_ROOT, filename)
    file_path = os.path.join(settings.BASE_DIR, path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/octet-stream")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    raise Http404

模板

{% extends 'base.html' %}

{% block content %}
Welcome, {{request.user.username}}
<table>
    <tr>
        <th>First Name: </th>
        <th>{{user.first_name}}</th>
    </tr>
    <tr>
        <th>Last Name: </th>
        <th>{{user.last_name}}</th>
    </tr>
    <tr>
        <th>Email: </th>
        <th>{{user.email}}</th>
    </tr>
    <tr>
        <th>Image: </th>
        {% if user.image %}
        <th><a href="{% url 'download' user.image%}"><img src="{{user.image.url}}" alt="IMage...." style="object-fit: cover;
            border-radius: 50%;
            height: 200px;
            width: 200px;"></a></th>
        {% endif %}
    </tr>
    <tr>
        <th>Address: </th>
        <th>{{user.address}}</th>
    </tr>
    <tr>
        <th>Bio: </th>
        <th>{{user.bio|linebreaks}}</th>
    </tr>
</table>

仅在函数参数中提供文件名,并在下载视图中设置文件路径。还将 content_type 设置为八位字节/流。

views.py

def download(request, filename):
    path = os.path.join(settings.MEDIA_ROOT, filename)
    file_path = os.path.join(settings.BASE_DIR, path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/octet-stream")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    raise Http404

template

{% extends 'base.html' %}

{% block content %}
Welcome, {{request.user.username}}
<table>
    <tr>
        <th>First Name: </th>
        <th>{{user.first_name}}</th>
    </tr>
    <tr>
        <th>Last Name: </th>
        <th>{{user.last_name}}</th>
    </tr>
    <tr>
        <th>Email: </th>
        <th>{{user.email}}</th>
    </tr>
    <tr>
        <th>Image: </th>
        {% if user.image %}
        <th><a href="{% url 'download' user.image%}"><img src="{{user.image.url}}" alt="IMage...." style="object-fit: cover;
            border-radius: 50%;
            height: 200px;
            width: 200px;"></a></th>
        {% endif %}
    </tr>
    <tr>
        <th>Address: </th>
        <th>{{user.address}}</th>
    </tr>
    <tr>
        <th>Bio: </th>
        <th>{{user.bio|linebreaks}}</th>
    </tr>
</table>

Providing just the file name in the function parameter and set the filepath in the download view. Also set the content_type as octet/stream.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文