+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 };
}
};
Я не нашел способа обрабатывать загрузку файлов в sveltkit. Есть идеи? Файл небольшой.. так что проблем с загрузкой в память нет.
🤔 А знаете ли вы, что...
Svelte - это инновационный фронтенд-фреймворк, разработанный на языке JavaScript.
Вы можете просто получить экземпляр файла из данных формы и прочитать его с помощью одного из его методов, таких как text()
, stream()
или arrayBuffer()
. например
// 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()));
Запись файлов — довольно опасная операция, рекомендуется проверить, что имя файла на самом деле является просто именем, а не полным путем.