How to browse to a folder with plotly dash?

Viewed 7178

I am learning Python Dashboard. I know that there is a Dash core components upload allow to upload a file. What I need is load all of files in a folder. I would like to know how to use a core component to browse to a select folder then read all files in that folder.

Thanks in advance.

2 Answers

You can use the dash_core_components.Upload component and set multiple=True to upload multiple files. Here is an example: https://dash.plotly.com/dash-core-components/upload.

This, however, uploads all the contents of all the files at once. What you cannot do with it is just get the contents of a folder, so that you can upload the files one by one.

However, since your question is about uploading all files in a folder, this should do it.

It's possible to use the os built-in library to navigate the files inside the server hosting the Dash app - this means your computer if you are running locally, or on the VM if you are hosting on the cloud.

As mentioned by ThangNguyen, it's not possible to browse the files on the client side. So if your app is hosted on a cloud instance, it won't be able to read the files the computer you are using to visit the app.

If your goal is to indeed navigate the files on the server, then you can use the following code:

import os

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State

app = dash.Dash(__name__)
server = app.server

folders = ["images", "spreadsheets"]

controls = [
    dcc.Dropdown(
        id="dropdown",
        options=[{"label": x, "value": x} for x in folders],
        value=folders[0],
    )
]

app.layout = html.Div(
    [html.H1("File Browser"), html.Div(controls), html.Div(id="folder-files")]
)


@app.callback(Output("folder-files", "children"), Input("dropdown", "value"))
def list_all_files(folder_name):
    # This is relative, but you should be able
    # able to provide the absolute path too
    file_names = os.listdir(folder_name)

    file_list = html.Ul([html.Li(file) for file in file_names])

    return file_list


if __name__ == "__main__":
    app.run_server(debug=True)

Given a folder structure like this one:

folder structure

You should get the following app:

demo of the app in action

Related