我正在尝试上传图像及其数据。我正在使用multer上传图片。但是我不断收到这样的错误消息:
{
[Error: ENOENT: no such file or directory, open 'D:\works\fiverr-kiddiemmerce-be\assets\products\2019-09-13T16:18:26.393Z180911-Naver-x-Dispatch-Yeoreum-cosmic-girls-wjsn-41821990-2000-1333.jpg']
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path:
'D:\\works\\fiverr-kiddiemmerce-be\\assets\\products\\2019-09-13T16:18:26.393Z180911-Naver-x-Dispatch-Yeoreum-cosmic-girls-wjsn-41821990-2000-1333.jpg',
storageErrors: []
}
我怎样才能解决这个问题?我一点都不知道。这是我到目前为止所做的。
multer.js
const fs = require('fs');
const multer = require(`multer`);
const path = require(`path`);
const productPath = path.join(__dirname, `../../assets/products`);
const storage = multer.diskStorage({
destination: (req, file, cb) => {
if (file.fieldname.includes(`material_image`)) {
cb(null, materialPath);
} else if (file.fieldname.includes(`product_image`)) {
if (!fs.existsSync(productPath)) {
fs.mkdir(productPath, { recursive: true }, (err) => {
console.log(err);
});
}
cb(null, productPath);
}
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + file.originalname);
},
});
const filter = (req, file, cb) => {
if (file.mimetype === `image/png` || file.mimetype === `image/jpeg`) {
cb(null, true);
} else {
cb(null, false);
}
};
module.exports = {
upload: multer({
storage : storage,
limits : { fileSize: 720 * 1280 * 5 },
fileFilter : filter,
}),
};
这是productController.js(我要在其中上传图像)
const { upload } = require(`../utils/multer`);
const multer = require(`multer`);
module.exports = {
store: async (req, res) => {
const img_upload = upload.any();
img_upload(req, res, (err) => {
if (err instanceof multer.MulterError) {
res.end();
return;
} else if (err) {
console.log(`It always goes here`);
console.log(err);
res.end();
return;
}
// Do something if no error
});
}
}
最佳答案
在Windows中,您无法使用冒号:
创建文件,因此必须用短划线new Date().toISOString().replace(/:/g , "-")
替换冒号,或者通过添加Date.now()
而不是new Date().toISOString()
将其更改为时间戳。
关于node.js - 为什么Multer在NodeJS上产生errno -4058,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57931315/