如何在Django中上传文件至指定路径并在Plotly Dash模块访问?
解决方案
1. 完善Django文件上传逻辑,确保文件保存到指定路径
你的现有代码仅获取了上传文件对象,但未执行持久化保存操作。修改视图代码,实现文件存储到目标路径:
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import os import uuid # 定义目标存储路径(Windows路径需用原始字符串或双反斜杠) UPLOAD_DIR = r'C:\tmp\Uploads' @csrf_exempt def test_page(request): if request.method == 'POST': upload_file = request.FILES['document'] # 确保目标目录存在,不存在则自动创建 os.makedirs(UPLOAD_DIR, exist_ok=True) # 生成唯一文件名,避免覆盖已有文件 file_ext = os.path.splitext(upload_file.name)[1] unique_filename = f"{uuid.uuid4().hex}{file_ext}" file_path = os.path.join(UPLOAD_DIR, unique_filename) # 分块写入文件,适配大文件上传场景 with open(file_path, 'wb+') as destination: for chunk in upload_file.chunks(): destination.write(chunk) # 将文件路径存入session,方便后续Dash模块读取 request.session['uploaded_file_path'] = file_path return render(request, 'index.html')
2. 让Plotly Dash访问上传的文件
方式一:通过Session传递文件路径(适用于用户关联场景)
如果你的Dash应用嵌入在Django中(如使用django-plotly-dash),可从Django Session中读取已保存的文件路径:
import dash from dash import dcc, html, Input, Output import pandas as pd from django_plotly_dash import DjangoDash from django.contrib.sessions.models import Session from django.utils import timezone import os app = DjangoDash('FileReader') app.layout = html.Div([ html.Button('读取上传文件', id='load-btn'), html.Div(id='file-content') ]) @app.callback( Output('file-content', 'children'), Input('load-btn', 'n_clicks'), prevent_initial_call=True ) def load_uploaded_file(n_clicks): # 获取当前用户的Session并读取文件路径 session_key = dash.callback_context.request.session.session_key session = Session.objects.get(session_key=session_key, expire_date__gt=timezone.now()) file_path = session.get_decoded().get('uploaded_file_path') if file_path and os.path.exists(file_path): # 示例:读取CSV文件,可根据实际文件类型调整 df = pd.read_csv(file_path) return html.Pre(df.to_string()) return html.P('未找到有效上传文件')
方式二:直接扫描指定目录(适用于公共文件场景)
如果无需关联特定用户,可让Dash直接扫描C:\tmp\Uploads目录,读取目标文件:
import os import pandas as pd from dash import dcc, html, Input, Output from django_plotly_dash import DjangoDash app = DjangoDash('FileScanner') UPLOAD_DIR = r'C:\tmp\Uploads' app.layout = html.Div([ dcc.Dropdown( id='file-selector', options=[ {'label': filename, 'value': os.path.join(UPLOAD_DIR, filename)} for filename in os.listdir(UPLOAD_DIR) if os.path.isfile(os.path.join(UPLOAD_DIR, filename)) ], placeholder='选择上传的文件' ), html.Div(id='file-content') ]) @app.callback( Output('file-content', 'children'), Input('file-selector', 'value') ) def display_file_content(file_path): if file_path: df = pd.read_csv(file_path) return html.Pre(df.to_string()) return html.P('请选择一个文件')
关键注意事项
- 权限验证:确保运行Django和Dash的进程拥有
C:\tmp\Uploads目录的读写权限,否则会出现文件操作失败。 - 文件清理:定期清理目录中的旧文件,避免磁盘空间被占用。
- 安全校验:建议添加文件类型校验(如仅允许CSV、Excel等格式),防止恶意文件上传。
内容的提问来源于stack exchange,提问作者Paulo Henrique A S A
相关产品推荐
相关产品推荐

