Getting Hyperlink of image or uploading to Imgur?

I’m building an app which requires that I send a URL through an API. However I want to do the leg-work for the end user by allowing them to insert a URL or upload the file from a local computer & I would get the URL for them.

I know that Anvil integrates with google drive and I can store the image. Is there a way to get the URL of the stored image? Alternatively how would I access the file path such that I can use the Imgur api to send the actual image?

Thanks

Have you considered storing the uploaded image as a Media object in an Anvil data table or does it have to be uploaded to imgur? If you store in a data table, you will automatically get a URL for the image.

Caveat: I only learned about this yesterday so might not be the best solution!

Thanks for the answer!

That is a step in the right direction. Though I would need to upload massive amounts of images for a short period of time & would rather not take on the responsbity of deleting old content when imgur already does that automatically. Stll, this is one step closer. Thanks

If you’re working with data tables, you can store a datetime in the database. Then, each time you (eg) upload a new image, you can query all the images in the database (ordered by time, eg tables.order_by('upload_date')), and delete anything that’s too old.

Alternatively, if you do want to use the Imgur API, email support@anvil.works to get the imgurpython module installed in your server modules. You can then pass a Media object to a server function (from a FileLoader component), dump the file out to a temporary file using get_bytes(), then feed it into the API. Something like this, perhaps:

In a form:

  # ...on the client
  def button_1_click(self, **event_args):
    anvil.server.call("upload_img", self.file_loader_1.file)

In a server module:

@anvil.server.callable
def upload_img(img):
  filename = '/tmp/upload_%s' % random.SystemRandom().random()
  try:
    with open(filename, 'w') as f:
      f.write(img.get_bytes())
    # Do your imgur upload here.
    imgurpython.do_something_with_a_file(filename)
  finally:
    os.unlink(filename)

Hope that helps!

1 Like

Thanks. This is exactly what I needed.