简体   繁体   English

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

[英]How to let users download an excel file in a specific path in Django?

I am a beginner in Python Django. I am trying to let users download an excel file in a specific path in Django. My views.py is as follows.我是Python Django的初学者,我试图让用户在Django的特定路径下下载一个excel的文件,我的views.py如下。 As you can see, I want to let user download OOOO.xlsx in the path /mysite/upload/.如您所见,我想让用户在路径 /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

My urls.py is as follows.我的urls.py如下。

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

However, it keeps showing an error like this on my HTML page.但是,它在我的 HTML 页面上一直显示这样的错误。

< < 在此处输入图像描述 > >

Please help me to find the bug.请帮我找出错误。

You should use djangos FileResponse .你应该使用 djangos FileResponse Read here for more.阅读此处了解更多信息。

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)

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

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