3

I am using pocketbase and svelte.js. How can I upload pictures to pocketbase via an html input.

<script lang="ts">
    import { currentUser, pb } from './pocketbase';
    const axios = require('axios').default;

    const fileInput = document.getElementById('fileInput');

    async function uploadFile() {
        axios({
            method: 'post',
            url: 'http://127.0.0.1:8090/api/collections/images/records',
            data: {
                image: fileInput.file,
            }
        });
    }

</script>

<form enctype="multipart/form-data" method="post" on:submit={uploadFile}>
    <input type="file" name="fileInput" id="fileInput">
    <button type="submit">Upload</button>
</form>

Hector
  • 65
  • 8
  • 1
    You're querying an element that does not exist yet. You should not querying it anyway but binding it to a svelte variable. Also you shouldn't use CJS require client side with svelte. Also, you don't need axios, especially if you're using sveltekit which has an isomorphic fetch version. – Tonton-Blax Jan 26 '23 at 11:52
  • 1
    Take a look here: https://pocketbase.io/docs/files-handling/ – DSSO21 Jan 30 '23 at 14:58

1 Answers1

0

You need to use a FormData() instance instead of JSON.

Example:

let formData = new FormData();
        
formData.append('image', image); //here, image is an uploaded Image object

await pb.collection('posts').create(formData) //replace data accordingly

"Once added, you could create/update a Record and upload "documents" files by sending a multipart/form-data request using the Records create/update APIs."

Source

Astro Orbis
  • 67
  • 2
  • 12