I’m trying to upload an Excel file from my Apple iClould folder into a Data Table, all from within a Server Module. My problem is that the BlobMedia object I’m creating (and then uploading via app_table.add_row()) is using the 2nd parameter, the file path (which I can access in Terminal), as the content of the file as a string instead of the actual Excel file. Also, if I use the Name= keyword (instead of omitting it), I get an “unexpected keyword” error. Here’s my BlobMedia constructor:
f = anvil.BlobMedia(‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’, ‘~/Library/Mobile\ Documents/com~apple~CloudDocs/Data Call Manager/Test.xlsx’, Name=‘Test.xlsx’)
I’ve also found that after the above line of code, f.length = the length of the string, not the Excel file (which is 175K).
I searched the docs and forum, found numerous examples of working with BlobMedia, but I can’t seem to get this figured out. Help!
P.S. I tried changing the single backslash in the 2nd parameter to a double due to Python’s escaping, but it makes no difference.
This is definitely a documentation bug, which I will fix! To clarify:
The second parameter in the constructor is the contents of the file. You need to supply the bytes of the file as that argument (in Python 2, a string is an array of bytes):
file_contents = return_an_xls_as_a_string()
f = anvil.BlobMedia(
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
file_contents,
name='this_can_be_anything.xlsx'
)
So you need to get your Server Module to retrieve the file contents as a string of bytes. Does iCloud have an API you can use for that? (If so, anvil.http.request will construct a Media object for you automatically.)
Uploading files from your machine
Of course, to upload files from your machine, you can add a FileLoader component to a Form. Its file property is automatically a Media object with the correct name, contents and content type. To get it into a Server Module, pass it as an argument to a server function using anvil.server.call.
Shaun, FYI: I already successfully use the FileLoader in my app. I’m automating the creation of customer demo data, and I need to be able to automate the upload of some sample Excel files. Thanks for the help - I’m researching the iCloud API, although I could technically upload the Excel files from anywhere on my Mac.
Shaun, being that there’s no particular reason I need to be using iCloud to store my Excel files, I’m just going to use Anvil’s Google Drive service and load my files from there. KISS principle in action
Yeah, that’s the whole goal here. My users can upload a limited amount of files in my app - they’re stored in a Data Table and I use the FileUploader. But as mentioned earlier, I need to pre-populate on-demand a sample data set for new clients and demos, and that includes uploading some sample Excel files. I’m just trying to make it a one-push-button affair on my end regarding the sample data.