简体   繁体   中英

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. As you can see, I want to let user download OOOO.xlsx in the path /mysite/upload/.

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.

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.

< 在此处输入图像描述 >

Please help me to find the bug.

You should use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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