Search code examples
fileserverrendersveltefastapi

How could I fetch File to server and use its response to display on Svelte Frontend?


In the Svelt File:

import { FileDropzone } from "attractions";

File-Dropzone.svelte:

  async function acceptUpload(e) {
    ...some code...

          const fetchResponse = await fetch('http://localhost:5000/upload', {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({"document-array": fileParagraphs})
          });

          let jsonedResponse = await fetchResponse.json();
       -->   let responseArray = JSON.parse(jsonedResponse); - I want to use this in the main Svelte to display some content after user uploaded a file.

So the goal is to display the content from fetch made to FastAPI server. Fetch sends file Content that I get via FileDropzone from "attractions" for Svelte. I could only print response in the console as the function situated in another Svelte File.

I tried to transfer response to main Svelte and then update content on Web Page. But I don't know how to get variable's value from another Svelte file's function... I tried to export & import, but it seems impossible since the variable situated in the function.


Solution

  • You could get files from FileDropzone (or e.g. form) straight in the Main Svelte File using bind:files

    1. Move your functions to the main File.svelte
    2. Create a variable with an empty array to save files into it
    3. Add Bind to your <FileDropzone Tag in your case (or <Form)
    4. Now your new variable is filled with files!

    4.1) If needed, get bind value (files) via {} - then you could show this variable on screen. That´s pretty much how you render value on the page.

    Then you should have code look alike:

    let files = []; //<-- Create a new array initially.
    import { FileDropzone } from "attractions";
    function fetchServer(--> files array here <--) {
       //---your func body for fetching
    }
    </script>
    
    <main>
    
      <FileDropzone bind:files/> //<-- Now our files will go into a new array "files"
    <p>{fetchServer(files)}</p> //<-- Then we render its value on the Web Page.
    </main>