How do I upload files to pocketbase?

2.6k Views Asked by At

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>

1

There are 1 best solutions below

2
On

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

Here's an example:

const formData = new FormData();

formData.append('image', image); // here the image is appended to the form data

await pb.collection('posts').create(formData) // replace 'posts' with your collection

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.

From the pocketbase docs