Search code examples
filesvelteread-eval-print-loop

displaying file content in svelte


I am using this code to upload a file. And I want to display the content of the file but all I get is [object file] and nothing else. is there a way to display the file content in svelte?

file text2.txt:

1 2 3 4 5 6
7 8 9 10 11 1

Test.svelte:

    <script>
      import { onMount } from "svelte"
      // d3.csv(' http://127.0.0.1:8081/test.csv').then(function(data) {
      //   console.log(data[0])})
    
      let files;
      $: if (files) {
        console.log(files);
        for (const file of files) {
          console.log(`${file.name}: ${file.size} bytes`);
        }
      }
    
    </script>
    
    <p>...from test</p>
    
    <input type='file' bind:files>
    
    {#if files}
        <h2>Selected files:</h2>
        {#each Array.from(files) as file,i}
            <p>{file.name} ({file.size} bytes)</p>
                    <p>e: {file} i: {i}</p>
        {/each}
        <p>files length: {files.length}</p>
    {/if}

To reproduce this, just paste it into a svelte REPL.


Solution

  • After uploading a file you get an object of the type File, this is what allows you to do file.name and file.size. To get the actual content of this file you have to open a stream and then handle this stream. For simple files you can also you use .text() method which returns a promise that resolves with the text content. That means that you could use this promis in an #await block from 'svelte'

    {#each Array.from(files) as file, i}
      <p>{file.name} {file.size} bytes</p>
      {#await file.text() then text}
        <p>e: {text} i: {i}</p>
      {/await}
    {/each}