我是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页面上显示这样的错误。
<
请帮我找到窃听器。
1条答案
按热度按时间vybvopom1#
你应该使用djangos
FileResponse
。阅读这里了解更多。