【问题标题】:User-specific download file in djangodjango中用户特定的下载文件
【发布时间】:2021-10-10 19:07:53
【问题描述】:

我在 django 中有一个应用程序,它执行一些流程并构建一个文件,在一个部分中,我想向用户展示该文件以下载该文件。
(例如,用户在前端输入一个名字,应用程序给他一个 pdf 文件供他下载)。
文件构建过程正常,位于/app_dir/media/app/report/username/file.pdf 这是我的代码,但它不起作用,我遇到了一些问题。 你能帮帮我吗,我的问题在哪里? 以及如何使该用户特定于?每个用户都可以访问他的文件。


views.py (my_main_function):

@login_required(login_url='/login/')
def my_function(request):
    if request.method == 'GET':
        return render(request, 'app/my_function.html')

    else:
        try:
            #my main process to build .PDF file


        except ValueError:
            return render(request, 'app/dashboard.html', {'error':'Bad data passed in. Try again.'})

    return render(request, 'app/download.html')

views.py(下载功能):

def download_file(request):
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    filename = f"{file}.pdf"
    # Define the full file path
    filepath = f"{BASE_DIR}/app/media/app/reports/{user_name}/{filename}"
    # Open the file for reading content
    path =  open(filepath, 'rb')
    path.read()

    # Set the return value of the HttpResponse
    response = HttpResponse(path, content_type='application/pdf')
    # Set the HTTP header for sending to browser
    response['Content-Disposition'] = "attachment; filename=%s" % filepath
    # Return the response value
    return response

urls.py:

path('download/', views.download_file, name='download_file'),

简单测试下载.html文件:

<html>
    <title>Download File</title>
</head>
<body>
<enter>
   <h1>Download File using link</h1>
   <a href="{% url 'download_file' %}">Download PDF</a>
</center>
</body>
</html>

【问题讨论】:

  • 请将您的代码以文本形式发布,Stack Overflow 不接受截图。
  • @KlausD。抱歉,我编辑了它并添加了代码。

标签: python python-3.x django django-views


【解决方案1】:

不清楚您遇到了什么问题,但我会在您的代码中更正一些行

# first of all why not use django.http.FileResponse instead of HttpResponse?
# https://docs.djangoproject.com/en/3.2/ref/request-response/#fileresponse-objects
from django.http import FileResponse


# if you want files to be accessible only to owners 
# you probably should force user to login before download
@login_required
def download_file(request):
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    filename = f"{file}.pdf"
    filepath = f"{BASE_DIR}/app/media/app/reports/{user_name}/{filename}"
    
    # somewhere here you need to check if user has access to the file
    # if files ownership based solely on {user_name} dir in filesystem
    # then it is enough to check if file exists
    if os.path.exists(filepath):   
        response = FileResponse(open(filepath, 'rb'))

        # it is probably better to use filename instead of filepath
        response['Content-Disposition'] = "attachment; filename=%s" % filename

        return response
    else:
        raise Http404

【讨论】:

  • 感谢代码调整。我的问题是关于 open() 部分,我解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-06
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多