如何让用户在Django中的特定路径下下载excel文件?

iszxjhcz  于 2023-01-27  发布在  Go
关注(0)|答案(1)|浏览(165)

我是Python Django的初学者,我尝试让用户在Django中的特定路径下下载excel文件,我的views.py如下所示,正如你所看到的,我想让用户在路径/mysite/upload/下下载OOOO.xlsx。

def download_file(request):
    # Define Django project base directory
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # Define file name
    filename = 'OOOO.xlsx'
    # Define the full file path
    filepath = BASE_DIR + '/mysite/upload/' + filename
    # Open the file for reading content
    path = open(filepath, 'r')
    # Set the mime type
    mime_type, _ = mimetypes.guess_type(filepath)
    # Set the return value of the HttpResponse
    response = HttpResponse(path, content_type=mime_type)
    # Set the HTTP header for sending to browser
    response['Content-Disposition'] = "attachment; filename=%s" % filename
    # Return the response value
    return response

我的urls.py如下。

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('download/', views.download_file),
]

但是,它一直在我的HTML页面上显示这样的错误。
<

请帮我找到窃听器。

vybvopom

vybvopom1#

你应该使用djangos FileResponse。阅读这里了解更多。

def download_file(request):
    # Define Django project base directory
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # Define file name
    filename = 'OOOO.xlsx'
    # Define the full file path
    filepath = BASE_DIR + '/mysite/upload/' + filename
    return FileResponse(open(filepath, 'rb'), as_attachment=True)

相关问题