The dcc.Upload
component allows your app’s viewers to upload files,
like Excel spreadsheets or images, into your application.
Your Dash app can access the contents of an upload by listening to
the contents
property of the dcc.Upload
component.
contents
is a base64 encoded string that contains the files contents,
no matter what type of file: text files, images, .zip files,
Excel spreadsheets, etc.
Find a few usage examples below.
Here’s an example that parses CSV or Excel files and displays
the results in a Dash DataTable.
from dash import Dash, dcc, html, dash_table, Input, Output, State, callback
import base64
import datetime
import io
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
# Allow multiple files to be uploaded
multiple=True
),
html.Div(id='output-data-upload'),
])
def parse_contents(contents, filename, date):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename:
# Assume that the user uploaded a CSV file
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
print(e)
return html.Div([
'There was an error processing this file.'
])
return html.Div([
html.H5(filename),
html.H6(datetime.datetime.fromtimestamp(date)),
dash_table.DataTable(
df.to_dict('records'),
[{'name': i, 'id': i} for i in df.columns]
),
html.Hr(), # horizontal line
# For debugging, display the raw contents provided by the web browser
html.Div('Raw Content'),
html.Pre(contents[0:200] + '...', style={
'whiteSpace': 'pre-wrap',
'wordBreak': 'break-all'
})
])
@callback(Output('output-data-upload', 'children'),
Input('upload-data', 'contents'),
State('upload-data', 'filename'),
State('upload-data', 'last_modified'))
def update_output(list_of_contents, list_of_names, list_of_dates):
if list_of_contents is not None:
children = [
parse_contents(c, n, d) for c, n, d in
zip(list_of_contents, list_of_names, list_of_dates)]
return children
if __name__ == '__main__':
app.run(debug=True)
This next example responds to image uploads by displaying them
in the app with the html.Img
component.
from dash import Dash, dcc, html, Input, Output, State, callback
import datetime
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Upload(
id='upload-image',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
# Allow multiple files to be uploaded
multiple=True
),
html.Div(id='output-image-upload'),
])
def parse_contents(contents, filename, date):
return html.Div([
html.H5(filename),
html.H6(datetime.datetime.fromtimestamp(date)),
# HTML images accept base64 encoded strings in the same format
# that is supplied by the upload
html.Img(src=contents),
html.Hr(),
html.Div('Raw Content'),
html.Pre(contents[0:200] + '...', style={
'whiteSpace': 'pre-wrap',
'wordBreak': 'break-all'
})
])
@callback(Output('output-image-upload', 'children'),
Input('upload-image', 'contents'),
State('upload-image', 'filename'),
State('upload-image', 'last_modified'))
def update_output(list_of_contents, list_of_names, list_of_dates):
if list_of_contents is not None:
children = [
parse_contents(c, n, d) for c, n, d in
zip(list_of_contents, list_of_names, list_of_dates)]
return children
if __name__ == '__main__':
app.run(debug=True)
The children
attribute of the Upload
component accepts any
Dash component. Selecting the child element triggers the
upload action, as does dragging and dropping files.
Here are three different ways you can style the Upload
component using standard Dash components.
from dash import Dash, dcc, html
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Upload(html.Button('Upload File')),
html.Hr(),
dcc.Upload(html.A('Upload File')),
html.Hr(),
dcc.Upload([
'Drag and Drop or ',
html.A('Select a File')
], style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center'
})
])
if __name__ == '__main__':
app.run(debug=True)
Access this documentation in your Python terminal with:
```pythonhelp(dash.dcc.Upload)
```
Our recommended IDE for writing Dash apps is Dash Enterprise’s
Data Science Workspaces,
which has typeahead support for Dash Component Properties.
Find out if your company is using
Dash Enterprise.
children
(list of or a singular dash component, string or number | string; optional):
Contents of the upload component.
id
(string; optional):
The ID of this component, used to identify dash components in
callbacks. The ID needs to be unique across all of the components in
an app.
contents
(string | list of strings; optional):
The contents of the uploaded file as a binary string.
filename
(string | list of strings; optional):
The name of the file(s) that was(were) uploaded. Note that this does
not include the path of the file (for security reasons).
last_modified
(number | list of numbers; optional):
The last modified date of the file that was uploaded in unix time
(seconds since 1970).
accept
(string; optional):
Allow specific types of files. See
https://github.com/okonet/attr-accept for more information. Keep in
mind that mime type determination is not reliable across platforms.
CSV files, for example, are reported as text/plain under macOS but as
application/vnd.ms-excel under Windows. In some cases there might not
be a mime type set at all. See:
https://github.com/react-dropzone/react-dropzone/issues/276.
disabled
(boolean; default False
):
Enable/disable the upload component entirely.
disable_click
(boolean; default False
):
Disallow clicking on the component to open the file dialog.
max_size
(number; default -1
):
Maximum file size in bytes. If -1
, then infinite.
min_size
(number; default 0
):
Minimum file size in bytes.
multiple
(boolean; default False
):
Allow dropping multiple files.
className
(string; optional):
HTML class name of the component.
className_active
(string; optional):
HTML class name of the component while active.
className_reject
(string; optional):
HTML class name of the component if rejected.
className_disabled
(string; optional):
HTML class name of the component if disabled.
style
(dict; optional):
CSS styles to apply.
style_active
(dict; default { borderStyle: 'solid', borderColor: '#6c6', backgroundColor: '#eee',}
):
CSS styles to apply while active.
style_reject
(dict; default { borderStyle: 'solid', borderColor: '#c66', backgroundColor: '#eee',}
):
CSS styles if rejected.
style_disabled
(dict; default { opacity: 0.5,}
):
CSS styles if disabled.
loading_state
(dict; optional):
Object that holds the loading state object coming from dash-renderer.
loading_state
is a dict with keys:
component_name
(string; optional):
Holds the name of the component that is loading.
is_loading
(boolean; optional):
Determines if the component is loading or not.
prop_name
(string; optional):
Holds which property is loading.