我正在尝试为我的流媒体应用程序创建下载功能。但是我目前拥有的允许我通过流媒体应用程序上的按钮下载一个 zip 文件,但不幸的是它也将它保存到我的本地文件夹中。我不希望它保存到我的本地文件夹。问题是当我初始化 file_zip 对象时。我希望特定名称的 zip 文件最好与用户上传的带有“.zip”扩展名的文件名称相同(即包含字符串文件名作为函数参数的数据文件)。但是每次我这样做时,它都会将 zip 文件保存在我的本地文件夹中。有没有替代方法?顺便说一句,我正在尝试将熊猫数据框列表保存到一个 zip 文件中。
def downloader(list_df, datafile, file_type):
file = datafile.name.split(".")[0]
#create zip file
with zipfile.ZipFile("{}.zip".format(file), 'w', zipfile.ZIP_DEFLATED) as file_zip:
for i in range(len(list_df)):
file_zip.writestr(file+"_group_{}".format(i)+".csv", pd.DataFrame(list_df[i]).to_csv())
file_zip.close()
#pass it to front end for download
zip_name = "{}.zip".format(file)
with open(zip_name, "rb") as f:
bytes=f.read()
b64 = base64.b64encode(bytes).decode()
href = f'<a href=\"data:file/zip;base64,{b64}\" download="{zip_name}">Click Here To Download</a>'
st.markdown(href, unsafe_allow_html=True)
听起来您想在内存中创建 zip 文件并稍后使用它来构建 base64 编码。您可以将io.BytesIO()
对象与 一起使用ZipFile
,倒带它,然后读回数据以进行 base64 编码。
import io
def downloader(list_df, datafile, file_type):
file = datafile.name.split(".")[0]
#create zip file
zip_buf = io.BytesIO()
with zipfile.ZipFile(zip_buf, 'w', zipfile.ZIP_DEFLATED) as file_zip:
for i in range(len(list_df)):
file_zip.writestr(file+"_group_{}".format(i)+".csv", pd.DataFrame(list_df[i]).to_csv())
zip_buf.seek(0)
#pass it to front end for download
zip_name = "{}.zip".format(file)
b64 = base64.b64encode(zip_buf.read()).decode()
del zip_buf
href = f'<a href=\"data:file/zip;base64,{b64}\" download="{zip_name}">Click Here To download</a>'
st.markdown(href, unsafe_allow_html=True)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句