上传图片错误 (NodeJs/Formidable)

Uploading Images error (NodeJs/Formidable)

我正在使用 formidable@2.0.1 上传内容图片,按照你的教程。我得到了以下内容。 如何调试这个错误?

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);

使用 multer npm 效果很好

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()


app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
 console.log(req.file, req.body)
})



在Controller.js中,我将files.image.path更改为files.image.filepath,并将files.image.type更改为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);
 });
});
};