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>
Few important points –
- In the input fields, we are using attribute binding to store values in variables like
bind:value
andbind:files
. - The
content-type
header is set tomultipart/form-data
so that file upload can work. - Replace
api_url_here
with the url on which you want to upload file, likehttps://www.example.com/uploadFile.php
. - Both
POST
as well asFILE
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.