我正在编写一个简单的 Python 应用程序,用户从本地文件管理器中选择一个文件并尝试使用 Streamlit 上传。
我能够使用 streamlit.uploader
成功获取用户提供的文件,并将该文件存储在 Streamlit 应用程序文件夹的临时目录中,但问题是我无法给出存储在新创建的目录中的文件的文件路径,以便将应用程序发送到我的 gcp 云存储桶中。
在任何帮助下面添加我的代码片段表示赞赏:)
import streamlit as st
from google.oauth2 import service_account
from google.cloud import storage
import os
from os import listdir
from os.path import isfile, join
from pathlib import Path
from PIL import Image, ImageOps
bucketName=('survey-appl-dev-public')
# Create API client.
credentials = service_account.Credentials.from_service_account_info(
st.secrets["gcp_service_account"]
)
client = storage.Client(credentials=credentials)
#create a bucket object to get bucket details
bucket = client.get_bucket(bucketName)
file = st.file_uploader("Upload An file")
def main():
if file is not None:
file_details = {"FileName":file.name,"FileType":file.type}
st.write(file_details)
#img = load_image(image_file)
#st.image(img, caption='Sunrise by the mountains')
with open(os.path.join("tempDir",file.name),"wb") as f:
f.write(file.getbuffer())
st.success("Saved File")
object_name_in_gcs_bucket = bucket.blob(".",file.name)
object_name_in_gcs_bucket.upload_from_filename("tempDir",file.name)
if __name__ == "__main__":
main()
我尝试使用cwd
命令导入文件的路径,并尝试使用操作系统库作为文件路径,但没有任何效果。
编辑:
我想要实现的只是使用 file_uploader
选项的保管箱进行客户选择的文件上传。在使用 file.getbuffer
选择文件后,我可以将文件保存到临时目录中,如代码所示,但我无法将代码上传到 gcs 存储桶中,因为它引用了因为当我按下上传按钮时,str 无法转换为 int。
也许是路径问题:
"the code is unable to find the path of the file stored in the temp directory"
但我无法弄清楚如何提供上传功能的路径。
我遇到的编码错误:
TypeError: '>' not supported between instances of 'str' and 'int'
Traceback:
File "/home/raviteja/.local/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 564, in _run_script
exec(code, module.__dict__)
File "/home/raviteja/test/streamlit/test.py", line 43, in <module>
main()
File "/home/raviteja/test/streamlit/test.py", line 29, in main
object_name_in_gcs_bucket = bucket.blob(".",file.name)
File "/home/raviteja/.local/lib/python3.10/site-packages/google/cloud/storage/bucket.py", line 795, in blob
return Blob(
File "/home/raviteja/.local/lib/python3.10/site-packages/google/cloud/storage/blob.py", line 219, in __init__
self.chunk_size = chunk_size # Check that setter accepts value.
File "/home/raviteja/.local/lib/python3.10/site-packages/google/cloud/storage/blob.py", line 262, in chunk_size
if value is not None and value > 0 and value % self._CHUNK_SIZE_MULTIPLE != 0:
最佳答案
感谢大家的回复,经过几天的挣扎,我终于发现了自己犯的错误。 我不知道我是对还是错,如果我错了请纠正我,但这对我有用:
object_name_in_gcs_bucket = bucket.blob("path-to-upload"+file.name)
将文件路径和文件名之间的 , 更改为 + 使我的问题得到解决。
抱歉,这个小问题。
很高兴我能解决这个问题。
关于python - 使用streamlit Python代码找不到上传文件的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74574390/