Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help needed for uploading files #149

Open
2 tasks done
Koikarp8877 opened this issue Mar 13, 2024 · 0 comments
Open
2 tasks done

Help needed for uploading files #149

Koikarp8877 opened this issue Mar 13, 2024 · 0 comments

Comments

@Koikarp8877
Copy link

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hello, i'm trying to upload files on my nextjs 14.0.4 app with fastify/busboy, however, while the files upload in the right repo, with the right name and right extension, they are unsuable "Not a JPEG file: starts with 0xef 0xbf", exemple with an jpeg file. I double checked the files are fine. It's my first nextjs app, any help would be greatly aprreciated. Thanks for your time.

import { PrismaClient } from '@prisma/client';
const Busboy = require('@fastify/busboy');
import fs from 'fs';
import path from 'path';
import os from 'os';

const prisma = new PrismaClient();

export const createRessource = async (req, res) => {
try {

const bb = new Busboy({ headers: req.headers, limits: { fileSize: 3000000 }, highWaterMark: undefined });
const formData = {};

bb.on('file', (fieldname, file, filename, encoding, mimetype) => {
  console.log(`File [${fieldname}]: filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`);

  const uniqueFilename = `${fieldname}-${Date.now()}-${path.basename(filename)}`;
  const saveTo = path.join('public', 'images', uniqueFilename);
  const buffers = [];

  file.on('data', (data) => {
    buffers.push(data);
    console.log(`File [${filename}] got ${data.length} bytes`);
  });

  file.on('end', () => {
    console.log(`File [${filename}] Finished`);
    const fileData = Buffer.concat(buffers);
    fs.writeFileSync(saveTo, fileData);
    console.log(`File [${filename}] save to [${saveTo}]`);
    formData[fieldname] = {
      filename: uniqueFilename,
      path: saveTo,
      mimetype: mimetype
    };
  });
});

bb.on('field', (fieldname, val) => {
  console.log(`Field [${fieldname}]: value: ${val}`);
  formData[fieldname] = val;
});

bb.on('finish', async () => {
  console.log('Done parsing form!');

  const { titre, contenu, categorieName, visibilite, filefield } = formData;
  const fileInfo = formData[filefield];

  const currentDate = new Date();

  const newRessource = await prisma.t_ressource.create({
    data: {
      ressource_titre: titre,
      ressource_date: currentDate,
      ressource_contenu: contenu,
      id_categorie: categorieName,
      ressource_media: fileInfo,
      ressource_visibilite: visibilite,
    },
  });

  console.log('Ressource créée:', newRessource);
  console.log('Nom du fichier :', fileInfo);

  res.json({
    success: true,
    message: 'Ressource créée avec succès',
    ressource: newRessource,
  });
});

bb.on('error', (err) => {
  console.error('Erreur lors du traitement du formulaire :', err);
  res.status(500).json({
    success: false,
    message: 'Erreur lors du traitement du formulaire',
  });
});

req.once('data', (chunk) => {
  bb.write(chunk);
});

bb.end(req.body);

} catch (error) {
console.error('Erreur lors de la création de la ressource:', error);
res.status(500).json({
success: false,
message: 'Erreur lors de la création de la ressource',
});
} finally {
await prisma.$disconnect();
}
}

My Environment

node version: v20.11.0
fastify version: >=2.0.0
os: Linux
Nextjs 14.0.4, prisma.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant