2

I want to create a file sharing website in with pynecone. Is there a go-to way to upload files and save them on the server?

The documentation says to use React components if there aren't any Pynecone specific components, but I wanted to know if Pynecone can handle files uploads on its own.

Milo Chen
  • 3,617
  • 4
  • 20
  • 36
madurin123
  • 31
  • 1

2 Answers2

3

This is not available yet, but is a high priority feature to add. There is an open ticket here. It should be available soon.

Nikhil Rao
  • 31
  • 3
2

Use pynecone.UploadFile.
The following is an example to show how to use it.

import pynecone as pc

class State(pc.State):
    """The app state."""

    # The image to show.
    img: str

    async def handle_upload(self, file: pc.UploadFile):
        """Handle the upload of a file.
        
        Args:
            file: The uploaded file.
        """
        upload_data = await file.read()
        outfile = f".web/public/{file.filename}"

        # Save the file.
        with open(outfile, "wb") as file_object:
            file_object.write(upload_data)

        # Update the img var.
        self.img = file.filename


def index():
    """The main view."""
    return pc.vstack(
        pc.upload(
            pc.button("Select File"),
            pc.text("Drag and drop files here or click to select files"),
            border="1px dotted black",
            padding="20em",
        ),
        pc.button(
            "Upload", 
            on_click=lambda: State.handle_upload(pc.upload_files())
        ),
        pc.image(src=State.img),
    )


# Add state and page to the app.
app = pc.App(state=State)
app.add_page(index, title="Upload")
app.compile()

By the way, there is a released upload example on pynecone-io So you can also refer to it too. https://github.com/pynecone-io/pynecone-examples/tree/main/upload

Milo Chen
  • 3,617
  • 4
  • 20
  • 36