Rodrigo Pereira
Rodrigo Pereira

Reputation: 1914

How to upload files - Sveltekit

+page.svelte

<form
    action="?/upload"
    method="post"
    enctype="multipart/form-data"
  >
<input
      type="file"
      name="file"
      id="file"
      accept="application/pdf"
    />

+page.server.js

export const actions = {
  upload: async ({ cookies, request, locals }) => {
    const data = await request.formData();

    //HOW CAN I GET and save the file locally with writeFileSync?

    return { success: true };
  }
};

I haven't found a way to handle file uploads in sveltkit. Any ideas? The file is small.. so there is no problem in loading to memory.

Upvotes: 6

Views: 10640

Answers (1)

brunnerh
brunnerh

Reputation: 184526

You can just get a File instance from the form data and read it via one of its methods like text(), stream() or arrayBuffer(). e.g.

// would recommend using these async functions
import { writeFile } from 'fs/promises';

//...

const file = data.get('file'); // value of 'name' attribute of input

await writeFile(`./files/${file.name}`, await file.text());
// or
await writeFile(`./files/${file.name}`, file.stream());
// or
await writeFile(`./files/${file.name}`, new Uint8Array(await file.arrayBuffer()));

Writing files is a fairly dangerous operation, would recommend validating that the file name is actually just a name, not a full path.

Upvotes: 11

Related Questions