본문 바로가기
Streamlit

[Streamlit] sidebar 메뉴, 파일 업로드 기능

by eyoo 2022. 5. 19.
sidebar 함수를 통해 웹의 왼쪽에 사이드바를 구성할수있다.
 
in:
menu = ['Image','CSV','About']
st.sidebar.selectbox('메뉴',menu)
out:
# sidebar 옆에 여러 함수를 입력해서 구성할수있다.
# 셀렉트박스를 사이드바에 적용시켰다.

 

 

이제 사이드바의 셀렉트박스를 고르면 해당 창이 나오도록 하자.

 

in:

if choice == menu[0]:
    st.subheader('이미지 파일 업로드')
elif choice == menu[1]:
    st.subheader('CSV 파일 업로드')
else:
    st.subheader('파일 업로드 프로젝트 입니다.')

out:

# if문에 리스트의 인덱스를 활용해 기능을 사용한다.

 

 

file_uploader 함수를 사용하여 사용자가 이미지 파일을 업로드 할수있도록 만들수있다.

 

in:

st.file_uploader('이미지 파일 선택',type=['jpg','png','jpeg'])

out:

# type 파라미터를 통해 이미지 파일의 형식을 지정해줘야 한다.

# 파라미터에 accept_multiple_files=True를 사용하여 여러개의 파일을 업로드 할수있다.

 
 
업로드 되는 파일의 파일명을 현재시간으로 설정하여 유니크하게 만들자.
 
in:
upload_file = st.file_uploader('이미지 파일 선택',type=['jpg','png','jpeg'])
if upload_file is not None:  #업로드 된 파일이 있으면 실행
    current_time = datetime.now()  #현재시간
    new_filename = current_time.isoformat().replace(':','_') + '.jpg'  #콜론을 언더바로 교체후 파일확장자
    upload_file.name = new_filename  #파일이름 설정
    save_uploaded_file('temp', upload_file)  #업로드 한 파일 저장

out:

# 파일이 save_uploaded_file 함수를 통해 저장된걸 확인할수 있다.

# save_uploaded_file의 첫 파라미터에는 저장될 폴더를, 두번째는 업로드되는 파일을 입력한다.

더보기

사용된 코드:

########파일 업로드 방법########
########이미지 파일, csv 파일 업로드########

from numpy import isfortran
from sklearn.ensemble import IsolationForest
import streamlit as st
from PIL import Image
import pandas as pd
import os
from datetime import datetime

# 디렉토리 정보와 파일을 알려주면, 해당 디렉토리에
# 파일을 저장하는 함수
def save_uploaded_file(directory, file) :
    # 1.디렉토리가 있는지 확인하여, 없으면 디렉토리부터만든다.
    if not os.path.exists(directory) :
        os.makedirs(directory)
    # 2. 디렉토리가 있으니, 파일을 저장.
    with open(os.path.join(directory, file.name), 'wb') as f :
        f.write(file.getbuffer())
    return st.success("Saved file : {} in {}".format(file.name, directory))

def main():
        # 사이드바 만들기

        st.title('파일 업로드 프로젝트')

        menu = ['Image','CSV','About']
        choice = st.sidebar.selectbox('메뉴',menu)

        if choice == menu[0]:
            st.subheader('이미지 파일 업로드')
            upload_file = st.file_uploader('이미지 파일 선택',type=['jpg','png','jpeg'])
            if upload_file is not None:  #있으면
                # print(upload_file.name)
                # print(upload_file.size)
                # print(upload_file.type)

                #파일명을 유니크하게 만들어서 저장
                # 현재시간을 활용해서 만든다.
                current_time = datetime.now()
                print(current_time.isoformat().replace(':','_'))
                new_filename = current_time.isoformat().replace(':','_') + '.jpg'
                upload_file.name = new_filename
                save_uploaded_file('temp', upload_file)




        elif choice == menu[1]:
            st.subheader('CSV 파일 업로드')

            upload_file = st.file_uploader('CSV 파일 선택',type=['csv'])

            if upload_file is not None:

            #파일명을 유니크하게 만들어서 저장
            # 현재시간을 활용해서 만든다.
                current_time = datetime.now()
                print(current_time.isoformat().replace(':','_'))
                new_filename = current_time.isoformat().replace(':','_') + '.csv'
                upload_file.name = new_filename
                save_uploaded_file('temp', upload_file)


                
        else:
            st.subheader('파일 업로드 프로젝트 입니다.')



if __name__ == '__main__':
    main()

 

 

 

 

 

댓글