dcc_upload

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.

Examples

Find a few usage examples below.

Displaying Uploaded Spreadsheet Contents

Here’s an example that parses CSV or Excel files and displays
the results in a Dash DataTable.

using Core: Typeof
using Dash
using Base64, Dates, CSV, DataFrames

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

app = dash(external_stylesheets=external_stylesheets)

app.layout = html_div([
    dcc_upload(
        id="upload-datan",
        children=html_div([
            "Drag and Drop or ",
            html_a("Select Files")
        ]),
        style=Dict(
            "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-uploadn"),
])

function parse_contents(contents, filename, date)
  content_type, content_string = split(contents, ',')
  decoded = base64decode(content_string)
  df = DataFrame()
  try
    if occursin("csv", filename)
      str = String(decoded)
      df =  CSV.read(IOBuffer(str), DataFrame)
    end
  catch e
    print(e)
    return html_div([
        "There was an error processing this file."
    ])
  end
  return html_div([
      html_h5(filename),
      html_h6(Libc.strftime(date)),

      dash_datatable(
          data=[Dict(pairs(NamedTuple(eachrow(df)[j]))) for j in 1:nrow(df)],
          columns=[Dict("name" =>i, "id" => i) for i in names(df)]
      ),

      html_hr(),  # horizontal line

      # For debugging, display the raw contents provided by the web browser
      html_div("Raw Content"),
      html_pre(string(contents[1:200], "..."), style=Dict(
          "whiteSpace" => "pre-wrap",
          "wordBreak" => "break-all"
      ))
  ])
end

callback!(
    app,
    Output("output-data-uploadn", "children"),
    Input("upload-datan", "contents"),
    State("upload-datan", "filename"),
    State("upload-datan", "last_modified"),
) do contents, filename, last_modified
  if !(contents isa Nothing)
      children = [
        parse_contents(c...) for c in
        zip(contents, filename, last_modified)]
      return children
  end
end

run_server(app, "0.0.0.0", debug=true)

Displaying Uploaded Images

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

using Dash
using Base64, Dates

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

app = dash(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=Dict(
            "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"),
])

function parse_contents_fig(contents, filename, date)
    return html_div([
        html_h5(filename),
        html_h6(Libc.strftime(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(string(contents[1:200],"..."), style=Dict(
            "whiteSpace" => "pre-wrap",
            "wordBreak" => "break-all"
        ))
    ])
end

callback!(
    app,
    Output("output-image-upload", "children"),
    Input("upload-image", "contents"),
    State("upload-image", "filename"),
    State("upload-image", "last_modified"),
) do contents, filename, last_modified
  if !(contents isa Nothing)
      children = [
        parse_contents_fig(c...) for c in
        zip(contents, filename, last_modified)]
      return children
  end
end

run_server(app, "0.0.0.0", debug=true)

Styling the Upload Component

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.

using Dash

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

app = dash(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")
    ], 
    id="upload-datag",
    style=Dict(
        "width" => "100%",
        "height" => "60px",
        "lineHeight" => "60px",
        "borderWidth" => "1px",
        "borderStyle" => "dashed",
        "borderRadius" => "5px",
        "textAlign" => "center"
    ))
])

run_server(app, "0.0.0.0", debug=true)



Upload Properties

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 (Array of or a singular dash component, String or Real | 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 | Array of Strings; optional):
The contents of the uploaded file as a binary string.

filename (String | Array 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 (Real | Array of Reals; 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 (Bool; default false):
Enable/disable the upload component entirely.

disable_click (Bool; default false):
Disallow clicking on the component to open the file dialog.

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

min_size (Real; default 0):
Minimum file size in bytes.

multiple (Bool; 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 (Bool; optional):
    Determines if the component is loading or not.

  • prop_name (String; optional):
    Holds which property is loading.