함수 정의
파일과 디렉토리를 알려주면 저장한다.
import streamlit as st
import os
def save_upload_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())
# 3. 파일 저장이 성공했으니, 화면에 성공했다고 보여주면서 리턴
return st.success('{}에 {}파일이 저장되었습니다.'.format(directory,file.name))
파일을 저장하는 방법
st.title('파일 업로드 프로젝트')
menu = ['Image','CSV','About']
# streamlit 으로 sidebar.selectbox 생성
choice = st.sidebar.selectbox('메뉴',menu)
# image를 선택했다면.
if choice == 'Image' :
st.subheader('이미지 파일 업로드')
# streamlit에 file_uploader 함수 사용, type= 확장자 지정
file= st.file_uploader('이미지를 업로드 하세요.',type=['jpg','jpeg','png'])
# file이 null인지 체크
if file is not None :
# 파일명을 일관성있게, 회사의 파일명 규칙대로 바꾼다.
# 현재시간을 조합하여 파일명을 만들면, 유니크하게 파일명을
# 지을 수 있다.
current_time = datetime.now()
current_time = current_time.isoformat().replace(':','_')
file.name = current_time + '.jpg'
# 바꾼파일명으로 temp 디렉토리에 저장한다.
save_upload_file('temp',file)
# 파일을 웹 화면에 나오게.
img = Image.open(file)
st.image(file)
만약 csv 로 하고 싶다면
st.subheader('CSV 파일 업로드')
file = st.file_uploader('CSV 파일 업로드',type=['csv'])
# 파일명을 유니크하게 만든다.
if file is not None :
# 파일명을 일관성있게, 회사의 파일명 규칙대로 바꾼다.
# 현재시간을 조합하여 파일명을 만들면, 유니크하게 파일명을
# 지을 수 있다.
current_time = datetime.now()
current_time = current_time.isoformat().replace(':','_')
file.name = current_time + '.csv'
# 파일을 서버에 저장한다.
save_upload_file('csv',file)
# 파일을 웹화면에 나타낸다.
df = pd.read_csv(file)
st.dataframe(df)
'개발 > 대시보드' 카테고리의 다른 글
웹 대시보드 - 차트 그리기(scatter,regplot,hist,altair,map,plotly) (0) | 2022.12.13 |
---|---|
웹 대시보드 - sidebar 를 사용할 때 파일을 분리하여 개발하는 방법. (0) | 2022.12.13 |
웹 대시보드 - 입력받기(input) (0) | 2022.12.13 |
웹 대시보드 - 여러 UI 함수 4(Image,video) (0) | 2022.12.12 |
웹 대시보드 - 여러 UI 함수 3(button,radio,checkbox,selectbox,multiselect,slider,expander) (0) | 2022.12.12 |