question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Enable file_uploader widget to provide information on file name and/ or type

See original GitHub issue

Problem

If you allow your user to upload multiple types of files like [“csv”, “xlsx”] or [“png”, “jpg”] then you have to develop some algorithm to determine the type of file your self. You don’t know the file name either.

Solution

Return the filename together with the file object either by adding it as a name attribute to the BytesIO or StringIO object. Or by returning a tuple of (file, name).

Additional context

I experienced this problem when developing the file_uploader example for awesome-streamlit.org.

file_uploader

"""Streamlit v. 0.52 ships with a first version of a **file uploader** widget. You can find the
**documentation**
[here](https://streamlit.io/docs/api.html?highlight=file%20upload#streamlit.file_uploader).

For reference I've implemented an example of file upload here. It's available in the gallery at
[awesome-streamlit.org](https://awesome-streamlit.org).
"""
from enum import Enum
from io import BytesIO, StringIO
from typing import Union

import pandas as pd
import streamlit as st

STYLE = """
<style>
img {
    max-width: 100%;
}
</style>
"""

FILE_TYPES = ["csv", "py", "png", "jpg"]


class FileType(Enum):
    """Used to distinguish between file types"""

    IMAGE = "Image"
    CSV = "csv"
    PYTHON = "Python"


def get_file_type(file: Union[BytesIO, StringIO]) -> FileType:
    """The file uploader widget does not provide information on the type of file uploaded so we have
    to guess using rules or ML

    I've implemented rules for now :-)

    Arguments:
        file {Union[BytesIO, StringIO]} -- The file uploaded

    Returns:
        FileType -- A best guess of the file type
    """

    if isinstance(file, BytesIO):
        return FileType.IMAGE
    content = file.getvalue()
    if (
        content.startswith('"""')
        or "import" in content
        or "from " in content
        or "def " in content
        or "class " in content
        or "print(" in content
    ):
        return FileType.PYTHON

    return FileType.CSV


def main():
    """Run this function to display the Streamlit app"""
    st.info(__doc__)
    st.markdown(STYLE, unsafe_allow_html=True)

    file = st.file_uploader("Upload file", type=FILE_TYPES)
    show_file = st.empty()
    if not file:
        show_file.info("Please upload a file of type: " + ", ".join(FILE_TYPES))
        return

    file_type = get_file_type(file)
    if file_type == FileType.IMAGE:
        show_file.image(file)
    elif file_type == FileType.PYTHON:
        st.code(file.getvalue())
    else:
        data = pd.read_csv(file)
        st.dataframe(data.head(10))

    file.close()


main()

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:12
  • Comments:16 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
svombergencommented, Dec 30, 2019

Agreed that we need some info on the uploaded file!

For just uploading a df, as a workaround, im using a simple try/except and let it throw the error in the last try:


def try_read_df(f):
    try:
        return pd.read_csv(f)
    except:
        return pd.read_excel(f)
    
if result:
    df = try_read_df(result)
    st.dataframe(df)
2reactions
karriebearcommented, Jul 7, 2020

We’re currently working on it and targeting early Q4!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Uploading files with a specific name - Uploadcare
Hi I would like to upload the file with a specific name using uploadcare widget. For example user on my site select a...
Read more >
Add a File Upload Widget | Web Developer Network
Adding a File Upload Widget​​ On the Administation toolbar, click Structure. Click the Content types link. LABEL: Enter the title for the widget...
Read more >
How to Create a File Upload Widget in WordPress (Step by ...
Step 1: Create Your File Upload Form in WordPress · Step 2: Configure File Upload Field Options · Step 3: Customize Your File...
Read more >
Enable End Users to Upload Files - OutSystems documentation
Enable End Users to Upload Files. Use the Upload widget to allow users to upload files, such as photos to your application.
Read more >
How to use file upload widget in OutSystems? - YouTube
Easily add a file upload widget to your screens so users can upload files and attachments to your applications.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found