Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading Images error (NodeJs/Formidable)

I was using [email protected] to upload form that contents image, following a tutorial thou. I got the below. How to debug this error?

Error: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined

Controller.js

const formidable = require("formidable");
const _ = require("lodash");
const fs = require("fs");
const Project = require("../models/projectModel");

exports.create = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;

form.parse(req, (err, fields, files) => {
if (err) {
  return res.status(400).json({
    error: "Image could not be uploaded",
  });
}
let project = new Project(fields);

if (files.image) {
  project.image.data = fs.readFileSync(files.image.path);

  project.image.contentType = files.image.type;
}

project.save((err, result) => {
  if (err) {
    return res.status(400).json({
      error: errorHandler(error),
    });
  }
  res.json(result);
});
});
};

projectModel.js

const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;

const projectSchema = new mongoose.Schema(
 {
title: {
  type: String,
  trim: true,
  require: true,
 },
 category: {
  type: ObjectId,
  ref: "Category",
  required: true,
 },
 image: {
  data: Buffer,
  contentType: String,
 },
},
{
timestamps: true,
}
);

module.exports = mongoose.model("Project", projectSchema);
like image 937
Hassan Ademuyiwa Avatar asked May 05 '26 20:05

Hassan Ademuyiwa


1 Answers

In Controller.js I changed files.image.path to files.image.filepath and also changed files.image.type to files.image.mimetype

Controller.js

const formidable = require("formidable");
const _ = require("lodash");
const fs = require("fs");
const Project = require("../models/projectModel");

exports.create = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;

form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
error: "Image could not be uploaded",
 });
}
let project = new Project(fields);

if (files.image) {
project.image.data = fs.readFileSync(files.image.filepath);

project.image.contentType = files.image.mimetype;
}

project.save((err, result) => {
if (err) {
return res.status(400).json({
  error: errorHandler(error),
});
}
res.json(result);
 });
});
};
like image 92
Hassan Ademuyiwa Avatar answered May 08 '26 10:05

Hassan Ademuyiwa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!