file-upload.ts 969 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use server';
  2. import { prisma } from '@/lib/prisma';
  3. export async function uploadFile(file: File) {
  4. try {
  5. const bytes = await file.arrayBuffer();
  6. const buffer = Buffer.from(bytes);
  7. const uploadedFile = await prisma.file.create({
  8. data: {
  9. filename: file.name,
  10. mimetype: file.type,
  11. size: file.size,
  12. data: buffer,
  13. },
  14. });
  15. return { success: true, data: uploadedFile };
  16. } catch (error) {
  17. console.error('Error uploading file:', error);
  18. return { success: false, error: 'Failed to upload file' };
  19. }
  20. }
  21. export async function getFileById(id: string) {
  22. try {
  23. const file = await prisma.file.findUnique({
  24. where: { id },
  25. });
  26. if (!file) {
  27. return { success: false, error: 'File not found' };
  28. }
  29. return { success: true, data: file };
  30. } catch (error) {
  31. console.error('Error fetching file:', error);
  32. return { success: false, error: 'Failed to fetch file' };
  33. }
  34. }