import { writeFileSync, mkdirSync, existsSync } from 'fs'; import { fail } from '@sveltejs/kit'; import type { RequestEvent } from './$types'; import safePath from '$lib'; import { hash } from 'crypto'; import path from 'path'; const storagePath: string = './uploads'; const mkdirIfNotExists = (path: string) => { if (!existsSync(path)) { mkdirSync(path); } }; export const actions = { default: async ({ request }: RequestEvent) => { const data = await request.formData(); const formFiles = data.getAll('files'); if (!formFiles) { return fail(400, { field: 'files', files: formFiles, missing: true }); } else if (!(formFiles as File[])) { return fail(400, { field: 'files', files: formFiles, incorrect: true }); } const files = formFiles as File[]; console.log(files); if (files.length === 0) { return fail(400, { field: 'files', files: formFiles, empty: true }); } const formName = data.get('name'); if (!formName) { return fail(400, { field: 'name', name: formName, missing: true }); } else if (!(formName as string)) { return fail(400, { field: 'name', name: formName, incorrect: true }); } const name = safePath(formName as string); files.forEach(async (file) => { const outPath = `${storagePath}/${name}`; const content = Buffer.from(await file.arrayBuffer()); const ext = path.extname(file.name); mkdirIfNotExists(outPath); const filename = hash('sha1', content); const fullPath = `${outPath}/${filename}${ext}`; if (existsSync(fullPath)) { console.warn(`${fullPath} has already been uploaded. Skipping...`); } else { writeFileSync(fullPath, Buffer.from(await file.arrayBuffer()), { flag: 'a+' }); } }); return { success: true }; } };