Getting a missing file or ID parameters on API call

I have a dashboard where I input a userId, an influencerId and a image that are then pushed to a Google Bucket.

When I try to upload the image after entering the different fields, I’m getting this :

✓ Compiled /api/upload in 447ms (924 modules) API resolved without sending a response for /api/upload, this may result in stalled requests. Received fields: [Object: null prototype] {} Received file: undefined Missing file or ID parameters POST /api/upload 400 in 523ms

The browser console logs :

Form Data Values: page.tsx:42 file: ddd.png page.tsx:42 userId: 66466669db9da50c2fdcaaf6 page.tsx:42 influencerId: 25800f88-2f87-427e-bcca-ae5f257de065

Here is the code of the dashboard page :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"use client";
import React, { useState } from "react";
import axios from "axios";
import { auth } from "@clerk/nextjs/server";
import { redirect } from "next/navigation";
export default function AdminDashboard() {
//const { sessionClaims } = auth();
// If the user does not have the admin role, redirect them to the home page
//if (sessionClaims?.metadata.role !== "admin") {
//redirect("/");
//return null; // This prevents the component from rendering on the client-side
//}
const [file, setFile] = useState(null);
const [userId, setUserId] = useState("");
const [influencerId, setInfluencerId] = useState("");
const handleFileChange = (event) => {
if (event.target.files && event.target.files.length > 0) {
setFile(event.target.files[0]);
console.log("Selected file:", event.target.files[0]);
}
};
const handleSubmit = async (event) => {
event.preventDefault();
if (!file || !userId || !influencerId) {
alert("All fields are required");
return;
}
const formData = new FormData();
formData.append("file", file);
formData.append("userId", userId);
formData.append("influencerId", influencerId);
console.log("Form Data Values:");
for (let [key, value] of formData.entries()) {
console.log(`${key}: ${value instanceof Blob ? value.name : value}`);
}
try {
const response = await axios.post("/api/upload", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
console.log("Server response:", response.data);
alert("File uploaded successfully");
} catch (error) {
console.error("Upload error:", error.response || error);
alert("Error uploading file");
}
};
return (
<>
<h1>Admin Dashboard</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
value={userId}
onChange={(e) => setUserId(e.target.value)}
placeholder="User ID"
required
/>
<input
type="text"
value={influencerId}
onChange={(e) => setInfluencerId(e.target.value)}
placeholder="Influencer ID"
required
/>
<input type="file" onChange={handleFileChange} required />
<button type="submit">Upload Image</button>
</form>
</>
);
}
</code>
<code>"use client"; import React, { useState } from "react"; import axios from "axios"; import { auth } from "@clerk/nextjs/server"; import { redirect } from "next/navigation"; export default function AdminDashboard() { //const { sessionClaims } = auth(); // If the user does not have the admin role, redirect them to the home page //if (sessionClaims?.metadata.role !== "admin") { //redirect("/"); //return null; // This prevents the component from rendering on the client-side //} const [file, setFile] = useState(null); const [userId, setUserId] = useState(""); const [influencerId, setInfluencerId] = useState(""); const handleFileChange = (event) => { if (event.target.files && event.target.files.length > 0) { setFile(event.target.files[0]); console.log("Selected file:", event.target.files[0]); } }; const handleSubmit = async (event) => { event.preventDefault(); if (!file || !userId || !influencerId) { alert("All fields are required"); return; } const formData = new FormData(); formData.append("file", file); formData.append("userId", userId); formData.append("influencerId", influencerId); console.log("Form Data Values:"); for (let [key, value] of formData.entries()) { console.log(`${key}: ${value instanceof Blob ? value.name : value}`); } try { const response = await axios.post("/api/upload", formData, { headers: { "Content-Type": "multipart/form-data", }, }); console.log("Server response:", response.data); alert("File uploaded successfully"); } catch (error) { console.error("Upload error:", error.response || error); alert("Error uploading file"); } }; return ( <> <h1>Admin Dashboard</h1> <form onSubmit={handleSubmit}> <input type="text" value={userId} onChange={(e) => setUserId(e.target.value)} placeholder="User ID" required /> <input type="text" value={influencerId} onChange={(e) => setInfluencerId(e.target.value)} placeholder="Influencer ID" required /> <input type="file" onChange={handleFileChange} required /> <button type="submit">Upload Image</button> </form> </> ); } </code>
"use client"; 

import React, { useState } from "react";
import axios from "axios";
import { auth } from "@clerk/nextjs/server";
import { redirect } from "next/navigation";

export default function AdminDashboard() {
  //const { sessionClaims } = auth();

  // If the user does not have the admin role, redirect them to the home page
  //if (sessionClaims?.metadata.role !== "admin") {
  //redirect("/");
  //return null; // This prevents the component from rendering on the client-side
  //}

  const [file, setFile] = useState(null);
  const [userId, setUserId] = useState("");
  const [influencerId, setInfluencerId] = useState("");

  const handleFileChange = (event) => {
    if (event.target.files && event.target.files.length > 0) {
      setFile(event.target.files[0]);
      console.log("Selected file:", event.target.files[0]);
    }
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (!file || !userId || !influencerId) {
      alert("All fields are required");
      return;
    }

    const formData = new FormData();
    formData.append("file", file);
    formData.append("userId", userId);
    formData.append("influencerId", influencerId);

    console.log("Form Data Values:");
    for (let [key, value] of formData.entries()) {
      console.log(`${key}: ${value instanceof Blob ? value.name : value}`);
    }

    try {
      const response = await axios.post("/api/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      console.log("Server response:", response.data);
      alert("File uploaded successfully");
    } catch (error) {
      console.error("Upload error:", error.response || error);
      alert("Error uploading file");
    }
  };

  return (
    <>
      <h1>Admin Dashboard</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={userId}
          onChange={(e) => setUserId(e.target.value)}
          placeholder="User ID"
          required
        />
        <input
          type="text"
          value={influencerId}
          onChange={(e) => setInfluencerId(e.target.value)}
          placeholder="Influencer ID"
          required
        />
        <input type="file" onChange={handleFileChange} required />
        <button type="submit">Upload Image</button>
      </form>
    </>
  );
}

And the upload.js :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { createRouter } from "next-connect";
import multer from "multer";
import path from "path";
import { uploadFile } from "../../lib/google.bucket";
import InfluencerModel from "../../lib/database/models/influencer.model";
import { connectToDatabase } from "../../lib/database/mongoose";
const upload = multer({ storage: multer.memoryStorage() });
const router = createRouter();
router.post("/api/upload", upload.single("file"), async (req, res) => {
try {
console.log("Received fields:", req.body);
console.log("Received file:", req.file);
const userId = req.body.userId;
const influencerId = req.body.influencerId;
const file = req.file;
if (!file || !userId || !influencerId) {
console.log("Missing file or ID parameters");
return res.status(400).json({ message: "Missing file or ID parameters" });
}
const filename = path.basename(
file.originalname,
path.extname(file.originalname)
);
const extension = path.extname(file.originalname).slice(1);
const filePathInBucket = `user-${userId}/influencer-${influencerId}/${filename}.${extension}`;
const fileUrl = await uploadFile(filePathInBucket, file.buffer);
await connectToDatabase();
const influencer = await InfluencerModel.findOne({ influencerId });
if (!influencer) {
return res.status(404).json({ message: "Influencer not found" });
}
influencer.images.push({ uri: fileUrl });
await influencer.save();
res.status(200).json({
message: "File uploaded and record updated successfully",
fileUrl,
});
} catch (error) {
console.error("Error processing upload:", error);
res.status(500).json({ message: "Internal server error" });
}
});
export default router.handler();
</code>
<code>import { createRouter } from "next-connect"; import multer from "multer"; import path from "path"; import { uploadFile } from "../../lib/google.bucket"; import InfluencerModel from "../../lib/database/models/influencer.model"; import { connectToDatabase } from "../../lib/database/mongoose"; const upload = multer({ storage: multer.memoryStorage() }); const router = createRouter(); router.post("/api/upload", upload.single("file"), async (req, res) => { try { console.log("Received fields:", req.body); console.log("Received file:", req.file); const userId = req.body.userId; const influencerId = req.body.influencerId; const file = req.file; if (!file || !userId || !influencerId) { console.log("Missing file or ID parameters"); return res.status(400).json({ message: "Missing file or ID parameters" }); } const filename = path.basename( file.originalname, path.extname(file.originalname) ); const extension = path.extname(file.originalname).slice(1); const filePathInBucket = `user-${userId}/influencer-${influencerId}/${filename}.${extension}`; const fileUrl = await uploadFile(filePathInBucket, file.buffer); await connectToDatabase(); const influencer = await InfluencerModel.findOne({ influencerId }); if (!influencer) { return res.status(404).json({ message: "Influencer not found" }); } influencer.images.push({ uri: fileUrl }); await influencer.save(); res.status(200).json({ message: "File uploaded and record updated successfully", fileUrl, }); } catch (error) { console.error("Error processing upload:", error); res.status(500).json({ message: "Internal server error" }); } }); export default router.handler(); </code>
import { createRouter } from "next-connect";
import multer from "multer";
import path from "path";
import { uploadFile } from "../../lib/google.bucket";
import InfluencerModel from "../../lib/database/models/influencer.model";
import { connectToDatabase } from "../../lib/database/mongoose";

const upload = multer({ storage: multer.memoryStorage() });

const router = createRouter();

router.post("/api/upload", upload.single("file"), async (req, res) => {
  try {
    console.log("Received fields:", req.body);
    console.log("Received file:", req.file);

    const userId = req.body.userId;
    const influencerId = req.body.influencerId;
    const file = req.file;

    if (!file || !userId || !influencerId) {
      console.log("Missing file or ID parameters");
      return res.status(400).json({ message: "Missing file or ID parameters" });
    }

    const filename = path.basename(
      file.originalname,
      path.extname(file.originalname)
    );
    const extension = path.extname(file.originalname).slice(1);
    const filePathInBucket = `user-${userId}/influencer-${influencerId}/${filename}.${extension}`;
    const fileUrl = await uploadFile(filePathInBucket, file.buffer);

    await connectToDatabase();
    const influencer = await InfluencerModel.findOne({ influencerId });
    if (!influencer) {
      return res.status(404).json({ message: "Influencer not found" });
    }

    influencer.images.push({ uri: fileUrl });
    await influencer.save();

    res.status(200).json({
      message: "File uploaded and record updated successfully",
      fileUrl,
    });
  } catch (error) {
    console.error("Error processing upload:", error);
    res.status(500).json({ message: "Internal server error" });
  }
});

export default router.handler();

Any idea how to solve it ?

I can’t solve the issue

New contributor

0xAurora is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật