上传图片错误(NodeJs/Formidable)

问题描述 投票:0回答:4

我正在使用 [email protected] 上传内容图像,遵循教程。我得到了下面的。 如何调试这个错误?

错误:“path”参数必须是字符串类型或者 Buffer 或 URL 的实例。收到未定义

控制器.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);
node.js rest express backend formidable
4个回答
1
投票

在 Controller.js 中,我将

files.image.path
更改为
files.image.filepath
,还将
files.image.type
更改为
files.image.mimetype

控制器.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);
 });
});
};

0
投票

// 照片是 html 输入中给出的名称

<form action="/add" method="post" enctype="multipart/form-data">
<div class="form">
<div class="center">
<div class="form-input">
<label for="file-ip-1">Upload Image</label>
<input type="file" name="**photo**" id="file-ip-1" accept="image/*" onchange="showPreview(event);">
</div>
</div>
</form>

const express = require("express");
const Router = express.Router();
const User = require("../models/users");
const path = require("path");
const fs = require("fs");
const bodyParser = require("body-parser");

// var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });

// for image
const formidable = require("formidable");

Router.get("/", (err, res) => {
    res.render("index")
})

// create / insert

Router.post("/add", (req, res) => {

// for image
const form = new formidable.IncomingForm();

form.parse(req, (err, fields, file) => {
if (err) {
return res.status(400).json({ error: err })
}

let oldPath = file.photo[0].filepath;
let newPath = path.join("E:", "CRUD-MONGO-11-07-2023", "public", 'uploads') + '/' + file.photo[0].  originalFilename;

photo = file.photo[0].originalFilename;
console.log(photo);

let rawData = fs.readFileSync(oldPath)
fs.writeFile(newPath, rawData, function (err) {
if (err) {
console.log(err);
}
})

})
})

0
投票
Solution is to loop through the files and retrieve the details

const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = new formidable.IncomingForm();

    // Specify the directory where uploaded files will be stored
    form.uploadDir = path.join(__dirname, 'uploads');

    form.parse(req, (err, fields, files) => {
      if (err) {
        console.error(err);
        return;
      }
      var originalFilename,oldPath;
      console.log(files)
      const uploadedFiles = files.file;
      
      uploadedFiles.forEach((uploadedFile) => {
      originalFilename= uploadedFile.originalFilename;
      oldPath=uploadedFile.filepath;
        console.log(originalFilename);    
      });
      const newPath = path.join(form.uploadDir, originalFilename);

      fs.rename(oldPath, newPath, (err) => {
        if (err) {
          console.error(err);
          return;
        }

        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('File uploaded successfully');
      });
    });
  } else {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(`
      <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload File">
      </form>
    `);
  }
});

const port = 3000;
server.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

-2
投票

使用 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)
})



© www.soinside.com 2019 - 2024. All rights reserved.