Svelte – How to upload a file?

In order to upload in file in Svelte, we can use javascript FormData() api. First we will create a form with file input field and append the value to the formdata variable. Along with file, we can also append any other data which we want to send as POST variable. Then we can make a fetch request to upload file. The process is similar to uploading file in react.

Code Example

Let’s see the code for uploading file –

<script>
  let postVar;
  let fileVar;

  function submitForm(){
    event.preventDefault();

    const dataArray = new FormData();
    dataArray.append("superHeroName", postVar);
    dataArray.append("uploadFile", fileVar);

    fetch("api_url_here", {
      method: "POST",
      headers: [["Content-Type", "multipart/form-data"]],
      body: dataArray
    })
      .then(response => {
        // Successfully uploaded
      })
      .catch(error => {
        // Upload failed
      });
  }
</script>

<div>
  <form on:submit={submitForm}>
    <input
      type="text"
      bind:value={postVar}
      placeholder={"Superhero Name"}
    />
    <br />
    <input 
      type="file" 
      bind:files={fileVar} />
    <br />
    <input type="submit" />
  </form>
</div>

    Tweet this to help others

Few important points –

  1. In the input fields, we are using attribute binding to store values in variables like bind:value and bind:files.
  2. The content-type header is set to multipart/form-data so that file upload can work.
  3. Replace api_url_here with the url on which you want to upload file, like https://www.example.com/uploadFile.php.
  4. Both POST as well as FILE parameters are sent in same request.

First we declared two variables – postVar and fileVar. They will store an ordinary post value as well as files respectively.

In our <form> tag, we are calling submitForm() function. Don’t forget to use event.preventDefault() otherwise form will submit in its default html behavior and reload the application.

Next, we created a FormData() variable and appended the text field value and file value in it. With the help of fetch, we sent the data to the API.

If you are using php as backend then you can access the data using –

$_POST['superHeroName'] for text field value.

$_FILES['uploadFile'] for file field value.

You may learn more about formdata here

Live Demo

Open Live Demo