I want to save multiple pdf files from datatable into a zip file

Welcome to the Forum!

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.

  1. At the end of the with block, the file will be closed, so the variable img_zip won’t contain anything useful.
  2. 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.
  3. 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.

Alternatively, see tempfile — Generate temporary files and directories — Python 3.7.16 documentation for how to create a uniquely-named temporary file, to hold your data. The file ceases to exist once its with block ends, so you’d want your for loop to live inside the with, instead of vice versa.

2 Likes