How to upload file in NodeJs to PocketBase

718 Views Asked by At

I'm working on a project where I need to upload many PDF files to a PocketBase collection.

I have all the files on my computer and I'd like to upload them using nodejs and the PocketBase JavaScript SDK. PocketBase expects me to send the file as a [file object], which is not possible in nodejs.

Ideally the code would look something like that:

const fileObject = loadFile(pathToFile);

const entry = {
  nameField: "some-field",
  fileField: fileObject
}

await pb.collection("my-collection").create(entry)

I didn't find any bits of code that could help creating a loadFile function.

2

There are 2 best solutions below

0
On

You are supposed to send your form as multipart/form-data when uploading files to pocketbase.

Try:

const res = fetch(
  "http://127.0.0.1:8090/api/collections/my-collection/records",
  {
    method: "POST",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    body: myFormWhichHasFiles,
  }
)

Also, make sure you don't use JSON.stringify on your form when using multipart/form data.

Pro tip: if you leave out 'Content-type', it should default to multipart/form-data.

0
On

you can do it now by updating your SDK to 0.17 or more and sending File Object with no problem