Make your app handle files
Anvil has built-in support for uploading, storing, downloading, and manipulating files and other binary data.
Follow this quickstart to load files into your app, access their contents and properties, and display an image file on the page.
Log in to Anvil and click ‘create app’. Choose the Material Design theme.
You will see your app in the centre of the screen. On the right is the Toolbox, which contains components to drag-and-drop.
Drop a FileLoader into the page.
Now scroll to the bottom of the Properties Panel. There is a list of events for this FileLoader. Click the blue arrows next to ‘change’.
You will be taken to the Code View. The
runs when a file is loaded into the FileLoader:
def file_loader_1_change(self, file, **event_args): """This method is called when a new file is loaded into this FileLoader""" pass
There is a Python object named
file that represents whatever
file the user loads in. It is an Anvil
Add some print statements to output the properties and contents of the file:
def file_loader_1_change(self, file, **event_args): """This method is called when a new file is loaded into this FileLoader""" print("The file's name is: %s" % file.name) print("The number of bytes in the file is: %s" % file.length) print("The file's content type is: %s" % file.content_type) print("The file's contents are: '%s'" % file.get_bytes())
Now click the ‘Run’ button at the top of the screen.
You’ll see your app running. Click the ‘upload’ button - you will get a file selection dialog.
Upload a short text file. Here’s what happens if you upload a file containing the text
Anvil represents files as Media objects:
Stop the app and go back to the Design View of the Form Editor.
Drag-and-drop an Image component onto the page and change its
original_size in the Properties Panel:
Go back to the code view and modify the
file_loader_1_change event handler to this:
def file_loader_1_change(self, file, **event_args): """This method is called when a new file is loaded into this FileLoader""" self.image_1.source = file
Run your app again and upload an image file. Your image will be displayed in the app:
Click on the button below to clone a finished version of this app into your account.
Want more depth on this subject?
Read more about Files, Media and Binary Data to see what else you can do with Media Objects.
Media objects are a powerful way to handle binary data: Anvil supports storing, downloading, emailing, displaying as images, streaming into Server Modules, saving as temporary files in Server Modules, and more.
Want another quickstart?
Every quickstart is on the Quickstarts page.