It looks like your code was written to return an open file-handle across the Internet to your browser. There are several ways this code is broken.
At the end of the with block, the file will be closed, so the variable img_zip wonât contain anything useful.
Even if img_zip remained open, it refers to local storage on a Server computer, which may be thousands of miles away, across the internet, from the PC that invoked get_all_file_into_zip. That file-handle is useless on any other computer.
Even if img_zip actually contained the data, its value is not of a type that Anvil knows how to transmit across the wire. The types that it does know about are here: Valid arguments and return values.
And there we see something that can help: Media objects. An Anvil Media Object is essentially the contents of a binary file, such as your zipfile, with some additional information for transit, like the fileâs name and type. Anvil can return such an object from its Servers to your userâs browser.
I suggest that you take a look at Media objects. There you will find methods and tools for converting your someZipeFile.zip into a Media Object, so that the contents of your zipfile can be returned.
Also use Search, in the Documentation, and at the top of this web page, to find Tutorials, Examples, and relating to Media Objects. Youâll find plenty of examples, a few of which involve zip files.
Caution: as written, by creating your zipfile on disk, you are likely to have two different users trying to update the same someZipFile.zip at the same time. They will then get a mix of each otherâs data. Probably not what you want.
Solution: In Python, you can create binary âfilesâ in memory, instead. (See Pythonâs BytesIO.) This guarantees that each user sees only their own data.
Here is the updated code from my server side. It works successfully by writing all the pdf files from row[âpdfcolumnâ] into newzip and the function returns archive as a media object. I can also successfully download the zip file from the client side and open it successfully but the issue is how the pdf files are saved and presented on my local machine.
@anvil.server.callable
def get_multiple_pdf_into_ZipFile_from_datatable():
pdf_from_table = app_tables.my_table.search(tables.order_by('name',ascending=True))
with zipfile.ZipFile('archive.zip','w') as newzip:
for row in pdf_from_table:
with anvil.media.TempFile(row["pdfcolumn"]) as filename:
newzip.write(filename)
archive = anvil.media.from_file("archive.zip")
return archive
I can open the files as pdf on my local machine and it opens successfully but I want the pdf files from the datatable to already be saved into the zip file as pdf with the correct file name and extension. May you please assist me with that.
This is how the files look after downloading zipfile from anvil.