Add Api for song upload

This commit is contained in:
Esa Kataja
2024-10-12 16:21:06 +03:00
parent 6bf57ff672
commit d47631abe9
6 changed files with 315 additions and 8 deletions
+39
View File
@@ -0,0 +1,39 @@
import { json } from '@sveltejs/kit';
import { parseBuffer } from 'music-metadata';
import { writeFile } from 'fs/promises';
import { join } from 'path';
import { unlink } from 'fs/promises';
export const config = {
api: {
bodyParser: false
}
};
export async function POST({ request }) {
try {
const formData = await request.formData();
const file = formData.get('upload');
if (!file) {
return json({ error: 'No file uploaded' }, { status: 400 });
}
// Save the file temporarily
const buffer = await file.arrayBuffer();
const tempPath = join('/tmp', `upload_${Date.now()}_${file.name}`);
await writeFile(tempPath, Buffer.from(buffer));
// Parse metadata
const metadata = await parseBuffer(Buffer.from(buffer));
// Clean up the temporary file
// You might want to handle this asynchronously or use a try-finally block
await unlink(tempPath);
return json({ metadata });
} catch (error) {
console.error('Error processing file:', error);
return json({ error: 'Failed to process file' }, { status: 500 });
}
}