I want to get a media’s URLs accessible from anywhere on the web. This media is stored in a data table, and as the docs says: " some media objects provide a special URL, which is only valid for this browser session using this app. For example, the url of media from a data table is only valid in the session when it was generated."
How can I convert this special URL into a public URL?
If you do a search on the forum, at one point someone posted their code for how they did this using an HTTP endpoint. That’s the only way to get a permanent URL for a media object.
In my case, first, I created an ‘http_endpoint’ on the server-side that takes the ‘row_id’ and returns the media stored in the ‘html_body’ column:
# Serving HTML through public URL
@anvil.server.http_endpoint('/email/:row_id')
def get_file(row_id, **p):
row = app_tables.email.get_by_id(row_id)
if row is not None:
# Returning a Media object serves it as the HTTP response
return row['html_body']
else:
return anvil.server.HttpResponse(status='404')
Secondly, I created a function on the server-side that calls the endpoint with the ‘row_id’:
And finally, I created a function on the client-side that takes the ‘row_id’ from a grid table, passes it to the function ‘get_file_url_from_id(row_id)’ and opens the ‘media_url’ in a new tab:
# Function that opens the html_body in a new tab
def get_media_url(self, **properties):
if self.item['html_body'] is not None:
row_id = self.item.get_id()
media_url = anvil.server.call('get_file_url_from_id', row_id)
anvil.js.window.open(media_url, 'popup')
else:
Notification("HTML file does not exist.",
style="danger",
timeout=4,
).show()