3

I am trying to create a frontend page with NiceGUI in which I upload a file to a FastAPI backend using requests. I have tried some stuff which I found online, but to no avail

Thank you for the help!

PS. I am new to coding

from client I wrote:

def handle_upload(event: events.UploadEventArguments):
    ui.notify(f'Uploaded {event.name}')
    with event.content as f:
        print(f.read().decode())

files = {"file": ui.upload(on_upload=handle_upload)}
        r = requests.post("http://127.0.0.1:8000/docs#/default/create_upload_file_uploadfile__post")

ui.run()

ideally I would like to receive the file as a PDF, or in some way so I can read it
From server:

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File):
    # create a copy of the temp file to "Uploaded Files"
    with open(f"Uploaded Files\{file.filename}", "wb") as stored_file:
        shutil.copyfileobj(file.file, stored_file)
        stored_file_path = str(pathlib.Path().absolute()) + f"\\Uploaded Files\\{file.filename}"
  • 2
    I'm confused by `r = requests.post("http://127.0.0.1:8000/docs#/default/create_upload_file_uploadfile__post")` - there is no body to that request. From the code before, I don't know whether I'm missing something – roganjosh Mar 30 '23 at 18:51
  • The syntax `files = { "file": ui.upload...` looks strange. What do you want to accomplish with it? Also your request is executed on starting the NiceGUI script. Is that intended? And last: why do you have a NiceGUI app running (which itself is using FastAPI) and a separate FastAPI app? Are these running on different machines? The URL suggest otherwise... – Rodja Mar 30 '23 at 19:03
  • Yes, `files = ...` is strange, not sure what it is supposed to do. As far as I understand the `requests.post` is supposed to send the uploaded file to the FastAPI server, thus should move into the `handle_upload` function. – Falko Mar 30 '23 at 19:39
  • Thank you for the help! I am really trying to figure out FastAPI and NiceGUI, because they seem really awesome. Thank you for the input! I will try to do better – Alex Irimia Mar 31 '23 at 08:23
  • You can head over to our NiceGUI Discord server: https://discord.gg/TEpFeAaF4f. We also have a channel for general Python questions. – Rodja Mar 31 '23 at 14:05

0 Answers0