Reputation: 27
I want to download images from URLs stored in an .xslx file, zip them and use Streamlit's download button to download the zip file.
Running the code without st.download_button seems to work but I don't know how to introduce the download button to my code.
The code below gives me this error message.
RuntimeError: Invalid binary data format: <class 'zipfile.ZipFile'>
code:
import pandas as pd
import urllib.request
import zipfile
df = pd.read_excel("images.xlsx")
# Column containing the image names
title = df["Name"].tolist()
# Column containing the image urls
images = df["Image"].tolist()
with zipfile.ZipFile("images.zip", "w", zipfile.ZIP_DEFLATED) as z:
for idx,image in enumerate(images):
response = urllib.request.urlopen(image)
img_data = response.read()
z.writestr(title[idx], img_data)
st.download_button(
label="Download Images",
data=z,
file_name="images.zip",
mime="application/zip",
)
Upvotes: 0
Views: 2052
Reputation: 13225
As st.download_button
lists:
data (str or bytes or file)
zipfile.ZipFile
is just neither of those. However your code creates an actual images.zip
file, and that one is a file and can be supplied as the last example (with a flower.png
) shows on the same page. So putting the pieces together the result probably looks like this:
# create the file, from your code
with zipfile.ZipFile("images.zip", "w", zipfile.ZIP_DEFLATED) as z:
for idx,image in enumerate(images):
response = urllib.request.urlopen(image)
img_data = response.read()
z.writestr(title[idx], img_data)
# open it as a regular file and supply to the button as shown in the example:
with open("images.zip", "rb") as file:
btn = st.download_button(
label = "Download Images",
data = file,
file_name = "images.zip",
mime = "application/zip"
)
Upvotes: 1