+page.svelte

<form action="?/upload" method="post" enctype="multipart/form-data" > <input type="file" name="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.

1 Answer

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.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.