Upload content from Uppy widget to server

What I’m trying to do:
I am trying to upload a image using a Uppy.io widget.

What I’ve tried and what’s not working:
Uppy returns an object like this:

        {
            "source": "Dashboard",
            "id": "uppy-image/png-1e-image/png-8840-1694452544369",
            "name": "image.png",
            "extension": "png",
            "meta": {"relativePath": None, "name": "image.png", "type": "image/png"},
            "type": "image/png",
            "data": <File proxyobject>,
            "progress": {
                "percentage": 0,
                "bytesUploaded": 0,
                "bytesTotal": 8840,
                "uploadComplete": False,
                "uploadStarted": None,
            },
            "size": 8840,
            "isRemote": False,
            "remote": "",
            "preview": "blob:http://localhost:3032/262b526e-4c5e-4752-bb77-b31791e126fa",
        }

How can I convert this object to BlobMedia in order to upload it server?

Trying this

blob = anvil.BlobMedia(content_type=file.type, content=file.data, name=file.name)

But got this message: content must be a byte-string, not File

I’ll prepare a sample app if necessary.

If you’re just uploading to the server as a BlobMedia, then you’re better off using an Anvil FileLoader widget!

If you want the pretty preview of the image before uploading it, you can use an Image component, and on the FileLoader’s change event set the Image’s source to the file that just got uploaded. None of that sends data to the server, so it’s a client side preview, just like Uppy.

I’m using Uppy to take advantage of copy and paste features. Take a print screen, paste to Uppy and crop the image.

Can I mimic this feature using native Anvil components?

Managed to solve the problem using Uppy!

Used javascript FileReader to convert image to base64, then converted to bytes and to a BlobMedia!

    @anvil.js.report_exceptions
    def complete(self, result, *args):
        print("complete")
        for file in result["successful"]:
            reader = anvil.js.new(FileReader)
            reader.readAsDataURL(file.data)

            def on_load_end(*args):
                b64_str = reader.result.split(";base64,")[1]
                img_data = base64.b64decode(b64_str.encode())
                content = BlobMedia(file.type, img_data, file.name)

                anvil.server.call('upload', content)

            reader.onloadend = on_load_end
1 Like