next.js - How to upload a file to a distant server - Stack Overflow

I'm trying to upload an image via a form.I can't manage to make it work as I get the error:

I'm trying to upload an image via a form.

I can't manage to make it work as I get the error:

[TypeError: req.on is not a function]

⨯ unhandledRejection: [TypeError: req.on is not a function] ⨯ unhandledRejection: [TypeError: req.on is not a function]

Server-side:

import { NextApiRequest, NextApiResponse } from "next";
import formidable from "formidable";
import fs from "fs";
import path from "path";

export const config = {
    api: {
        bodyParser: false,
    },
};

export async function POST(req: NextApiRequest, res: NextApiResponse) {
    if (req.method !== "POST") {
        return res.status(405).json({ error: "Méthode non autorisée" });
    }

    const uploadDir = path.join(process.cwd(), ";);
    if (!fs.existsSync(uploadDir)) {
        fs.mkdirSync(uploadDir, { recursive: true });
    }

    const form = formidable({
        uploadDir: uploadDir,
        keepExtensions: true,
        maxFileSize: 10 * 1024 * 1024,
    });

    form.parse(req, (err, fields, files) => {
        if (err) {
            console.error("Erreur Formidable :", err);
            return res.status(500).json({ error: "Erreur pendant l'upload du fichier." });
        }

        console.log("Fichier téléversé !");
        const uploadedFile = files.myfile;

        return res.status(201).json({
            message: "Fichier envoyé avec succès !",
            file: uploadedFile,
        });
    });
}

and client-side:

"use client";

import { useState } from "react";
import Image from "next/image";

interface Content {
    title: string;
    file: File | null;
    alt: string;
    description: string;
}

export default function Home() {
    const [content, setContent] = useState<Content>({ title: "", file: null, alt: "", description: "" });

    const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files.length > 0) {
            setContent({ ...content, file: e.target.files[0] });
        }
    };

    const onSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        // Vérifie qu'un fichier est sélectionné
        if (!content.file) {
            alert("Veuillez sélectionner un fichier avant de soumettre !");
            return;
        }

        // FormData pour contenir les données à envoyer
        const fd = new FormData();
        fd.append("myfile", content.file); // Attache le fichier
        fd.append("title", content.title); // Ajoute d'autres champs si nécessaire

        try {
            // Téléversement du fichier vers l'API
            const response = await fetch("http://localhost:3000/api/addToGallery", {
                method: "POST",
                body: fd, // Le FormData est directement utilisé en tant que corps de requête
            });

            // Vérification de la réponse
            if (!response.ok) {
                throw new Error("Upload échoué : " + response.statusText);
            }

            const data = await response.json();
            console.log("Réponse du serveur :", data);

            alert("Fichier téléversé avec succès !");
        } catch (error) {
            console.error("Erreur lors de l'upload :", error);
            alert("Une erreur s'est produite lors de l'upload.");
        }
    };

I think the front is ok and the error comes from server-side.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744967156a4603750.html

相关推荐

  • next.js - How to upload a file to a distant server - Stack Overflow

    I'm trying to upload an image via a form.I can't manage to make it work as I get the error:

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信