下面是我的破折号应用程序的代码。问题在于所有浏览器类型都呈现空的图像缩略图或空的视频图像视频播放器。
所有这些文件都可以正常工作,就像我从文件夹中手动打开它们一样,它们可以正常工作。
import os
from dash import Dash, dcc, html, Input, Output
from dash.dependencies import State
import dash_bootstrap_components as dbc
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], title='Renderer')
app.layout = html.Div([
dbc.Row(
dbc.Col(
html.Div([
html.H1("Photo and Video Viewer"),
dcc.Dropdown(
id='file-type-dropdown',
options=[
{'label': 'Photos', 'value': 'photo'},
{'label': 'Videos', 'value': 'video'}
],
value='photo'
),
dcc.Dropdown(
id='file-dropdown',
options=[],
multi=True
),
html.Div(id='file-display')
]),
width=6),
),
])
@app.callback(
Output('file-dropdown', 'options'),
Output('file-dropdown', 'value'),
Input('file-type-dropdown', 'value')
)
def update_file_dropdown(selected_type):
folder_path = 'D:/New Folder' # Replace with the path to your folder
if selected_type == 'photo':
files = [f for f in os.listdir(folder_path) if f.endswith(('.jpg', '.jpeg', '.png',
'.gif'))]
else:
files = [f for f in os.listdir(folder_path) if f.endswith(('.mp4', '.avi', '.mkv',
'.mov'))]
file_options = [{'label': file, 'value': file} for file in files]
return file_options, None
@app.callback(
Output('file-display', 'children'),
Input('file-dropdown', 'value'),
State('file-type-dropdown', 'value')
)
def display_selected_files(selected_files, selected_type):
folder_path = 'D:/New Folder' # Replace with the path to your folder
if not selected_files:
return "Select files to display."
file_content = []
for file in selected_files:
file_path = os.path.join(folder_path, file)
if selected_type == 'photo':
if file_path.endswith(('.jpg', '.jpeg', '.png', '.gif')):
file_content.append(html.Img(src=file_path, style={'max-width': '100%'}))
else:
if file_path.endswith(('.mp4', '.avi', '.mkv', '.mov')):
file_content.append(html.Video(src=file_path, controls=True))
return file_content
if __name__ == '__main__':
app.run_server(debug=True, port=8060)
我哪里错了。
请指导。
问候 苏迪尔
出于安全考虑,当
window.location
不是本地资源时,大多数浏览器不允许加载本地资源。
在您的情况下,渲染的 html 页面包含使用本地文件路径引用的图像/视频,例如。
<img src="D:/New Folder/image.png">
,但由于页面是通过 http 从 http://hostname:8060
提供的,因此浏览器不允许使用 file://
方案来加载它们(如果页面是从 file:///path/to/some/page.html
加载的,那就会是这样)。
因此您还需要通过 http 提供这些资源:默认情况下,Dash 会自动提供
assets
文件夹中包含的所有文件
在应用程序目录的根目录中,因此您可以创建此文件夹并将应用程序所需的所有资源(js、css、medias 等)放入其中,然后在代码中您可以执行以下操作:
file_path = dash.get_asset_url(file) #os.path.join(folder_path, file)
铌。可以通过 Dash 构造函数设置有关资产的选项。
@see 在您的 Dash 应用程序中嵌入图像