當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Streamlit st.file_uploader用法及代碼示例

顯示文件上傳器小部件。

默認情況下,上傳的文件限製為 200MB。您可以使用server.maxUploadSize配置選項。有關如何設置配置選項的更多信息,請參閱https://docs.streamlit.io/library/advanced-features/configuration#set-configuration-options

函數簽名

st.file_uploader(label, type=None, accept_multiple_files=False, key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False)
參數說明

label (str)

一個簡短的標簽,向用戶解釋此文件上傳器的用途。

type (str or list of str or None)

允許的擴展名數組。 ['png', 'jpg'] 默認為無,表示允許所有擴展。

accept_multiple_files (bool)

如果為 True,則允許用戶同時上傳多個文件,在這種情況下,返回值將是文件列表。默認值:假

key (str or int)

一個可選的字符串或整數,用作小部件的唯一鍵。如果省略,將根據其內容為小部件生成一個 key 。相同類型的多個小部件可能不共享相同的鍵。

help (str)

顯示在文件上傳器旁邊的工具提示。

on_change (callable)

當此 file_uploader 的值更改時調用的可選回調。

args (tuple)

傳遞給回調的可選參數元組。

kwargs (dict)

一個可選的 kwargs 字典傳遞給回調。

disabled (bool)

一個可選的布爾值,如果設置為 True,則禁用文件上傳器。默認值為假。此參數隻能由關鍵字提供。

返回說明

(None or UploadedFile or list of UploadedFile)

  • 如果 accept_multiple_files 為 False,則返回 None 或 UploadedFile 對象。
  • 如果 accept_multiple_files 為 True,則返回一個列表,其中包含上傳的文件作為 UploadedFile 對象。如果沒有上傳文件,則返回一個空列表。

UploadedFile 類是 BytesIO 的子類,因此它是"file-like"。這意味著您可以將它們傳遞到預期文件的任何位置。

例子

插入一次接受單個文件的文件上傳器:

uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
     # To read file as bytes:
     bytes_data = uploaded_file.getvalue()
     st.write(bytes_data)

     # To convert to a string based IO:
     stringio = StringIO(uploaded_file.getvalue().decode("utf-8"))
     st.write(stringio)

     # To read file as string:
     string_data = stringio.read()
     st.write(string_data)

     # Can be used wherever a "file-like" object is accepted:
     dataframe = pd.read_csv(uploaded_file)
     st.write(dataframe)

插入一次接受多個文件的文件上傳器:

uploaded_files = st.file_uploader("Choose a CSV file", accept_multiple_files=True)
for uploaded_file in uploaded_files:
     bytes_data = uploaded_file.read()
     st.write("filename:", uploaded_file.name)
     st.write(bytes_data)

相關用法


注:本文由純淨天空篩選整理自streamlit.io大神的英文原創作品 st.file_uploader。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。