Upload Component

The Dash 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.

Here’s an example that parses CSV or Excel files and displays
the results in a table. Note that this example uses the
DataTable from the
dash-table
project.

import base64
import datetime
import io

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

import pandas as pd


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.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(
            data=df.to_dict('records'),
            columns=[{'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'
        })
    ])


@app.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_server(debug=True)

This next example responds to image uploads by displaying them
in the app with the html.Img component.

import datetime

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

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.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'
        })
    ])


@app.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_server(debug=True)

The children attribute of the Upload component accepts any
Dash component. Clicking on the children element will trigger the
upload action, as will dragging and dropping files.
Here are a few different ways that you could style the upload
component using standard dash components.

import dash
import dash_core_components as dcc
import dash_html_components as html

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.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_server(debug=True)



dcc.Upload Component Properties

Access this documentation in your Python terminal with:
```python

help(dash_core_components.Upload)
```

children (a list of or a singular dash component, string or number | string; optional): Contents of the upload component

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

contents (string | list of strings; optional): The contents of the uploaded file as a binary string

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

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

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).

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.

last_modified (number | list of numbers; optional): The last modified date of the file that was uploaded in unix time (seconds since 1970).

loading_state (dict; optional): Object that holds the loading state object coming from dash-renderer. loading_state has the following type: dict containing keys ‘is_loading’, ‘prop_name’, ‘component_name’. Those keys have the following types:

  • is_loading (boolean; optional): Determines if the component is loading or not
  • prop_name (string; optional): Holds which property is loading
  • component_name (string; optional): Holds the name of the component that is loading

max_size (number; default -1): Maximum file size. If -1, then infinite

min_size (number; default 0): Minimum file size

multiple (boolean; default False): Allow dropping multiple files

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