feat: implement file upload functionality and create file serving endpoint
All checks were successful
Build Docker Image / build (push) Successful in 1m20s
All checks were successful
Build Docker Image / build (push) Successful in 1m20s
This commit is contained in:
@@ -3,6 +3,9 @@ import { character, devilFruit, arc, characterOverride } from '$lib/server/db/sc
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { fail } from '@sveltejs/kit';
|
||||
import type { PageServerLoad, Actions } from './$types';
|
||||
import { writeFile } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
import { existsSync, mkdirSync } from 'fs';
|
||||
|
||||
export const load: PageServerLoad = async () => {
|
||||
const [charactersData, devilFruits, arcs, overrides] = await Promise.all([
|
||||
@@ -101,8 +104,38 @@ export const actions: Actions = {
|
||||
|
||||
const updates: Record<string, any> = {};
|
||||
|
||||
// Handle file upload
|
||||
const pictureFile = formData.get('pictureFile') as File;
|
||||
const hasUploadedPicture = !!pictureFile && pictureFile.size > 0;
|
||||
if (hasUploadedPicture) {
|
||||
try {
|
||||
const uploadsDir = join(process.cwd(), 'uploads');
|
||||
if (!existsSync(uploadsDir)) {
|
||||
mkdirSync(uploadsDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Get file extension
|
||||
const extension = pictureFile.name.split('.').pop();
|
||||
const filename = `${id}.${extension}`;
|
||||
const filepath = join(uploadsDir, filename);
|
||||
|
||||
// Convert file to buffer and save
|
||||
const buffer = Buffer.from(await pictureFile.arrayBuffer());
|
||||
await writeFile(filepath, buffer);
|
||||
|
||||
// Update pictureUrl to point to the handler route
|
||||
updates.pictureUrl = `/uploads/${filename}`;
|
||||
} catch (error) {
|
||||
console.error('File upload error:', error);
|
||||
return fail(500, { error: 'Failed to upload file' });
|
||||
}
|
||||
}
|
||||
|
||||
formData.forEach((value, key) => {
|
||||
if (key !== 'id') {
|
||||
if (key !== 'id' && key !== 'pictureFile') {
|
||||
if (hasUploadedPicture && key === 'pictureUrl') {
|
||||
return;
|
||||
}
|
||||
// Handle integers (age, bounty, height, devilFruitId, arcId)
|
||||
if (key === 'age' || key === 'bounty' || key === 'height' || key === 'devilFruitId' || key === 'arcId') {
|
||||
const strValue = value as string;
|
||||
|
||||
Reference in New Issue
Block a user