我测试它与 Postman ,我面临着这个错误,我不能解决它。
错误:
node:internal/fs/utils:671 throw new ERR_INVALID_ARG_TYPE(propName,['string',' Buffer','URL'],path);
TypeError [ERR_INVALID_ARG_TYPE]:“path”参数必须是字符串类型,或者是Buffer或URL的示例。
我的代码:
const Blog = require("../models/blog");
const Category = require("../models/category");
const Tag = require("../models/tag");
const User = require("../models/user");
const formidable = require("formidable");
const slugify = require("slugify");
import { stripHtml } from "string-strip-html";
const _ = require("lodash");
const { errorHandler } = require("../helpers/dbErrorHandler");
const fs = require("fs");
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: err,
});
}
const { title, body, categories, tags } = fields;
let blog = new Blog();
blog.title = title;
blog.body = body;
blog.slug = slugify(title).toLowerCase();
blog.mtitle = `${title} | ${process.env.APP_NAME}`;
blog.mdesc = stripHtml(body.substring(0, 160)).result;
blog.postedBy = req.auth._id;
if (files.photo) {
if (files.photo.size > 10000000) {
return res.status(400).json({
error: "Image should be less than 1mb in size",
});
}
blog.photo.data = fs.readFileSync(files.photo.path);
blog.photo.contentType = files.photo.type;
}
blog.save((err, result) => {
if (err) {
return res.status(400).json({
error: err,
});
}
res.json(result);
});
});
};
2条答案
按热度按时间ru9i0ody1#
您需要使用
files.photo.filepath
而不是files.photo.path
您可以在Formidable文档中查看“文件使用”,网址为https://github.com/node-formidable/formidable#file
eyh26e7m2#
对我来说绝对有效。